# XSLT-like search in a Ruby Hash

**URL:** <https://www.ruby-forum.com/t/xslt-like-search-in-a-ruby-hash/194141>\
**Category:** Ruby\
**Created:** [August 31, 2010, 2:29am UTC](https://www.ruby-forum.com/t/xslt-like-search-in-a-ruby-hash/194141 "2010-08-31T02:29:15Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![pitosalas](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/a4c791/32.png) [@pitosalas](https://www.ruby-forum.com/u/pitosalas)\
**Post date:** [August 31, 2010, 2:29am UTC](https://www.ruby-forum.com/t/xslt-like-search-in-a-ruby-hash/194141/1 "2010-08-31T02:29:15Z")

</div>

I have a need for some relatively fancy searching in a hash, and I am  
wondering if there’s anything that does some kind of pattern matching on  
Hash contents.

Specifically here’s an example of what I would like to be able to write:  
[http://www.pastie.org/1127920](http://www.pastie.org/1127920)

Yes, I can write the iterators, collects, merges and what else, but  
nicer would be some kind of structured query syntax. Any ideas?

Thanks!

Pito

---

<div class="post-metadata">

**Author:** ![pitosalas](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/a4c791/32.png) [@pitosalas](https://www.ruby-forum.com/u/pitosalas)\
**Post date:** [August 31, 2010, 3:14am UTC](https://www.ruby-forum.com/t/xslt-like-search-in-a-ruby-hash/194141/2 "2010-08-31T03:14:55Z")

</div>

On 08/30/2010 05:29 PM, Pito S. wrote:

> Thanks!
> 
> Pito

Might be something useful here:

[http://eigenclass.org/hiki/Pattern+matching+over+Ruby+objects](http://eigenclass.org/hiki/Pattern+matching+over+Ruby+objects)

---

<div class="post-metadata">

**Author:** ![pitosalas](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/a4c791/32.png) [@pitosalas](https://www.ruby-forum.com/u/pitosalas)\
**Post date:** [August 31, 2010, 2:18pm UTC](https://www.ruby-forum.com/t/xslt-like-search-in-a-ruby-hash/194141/3 "2010-08-31T14:18:09Z")

</div>

2010/8/31 Pito S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> I have a need for some relatively fancy searching in a hash, and I am  
> wondering if there’s anything that does some kind of pattern matching on  
> Hash contents.
> 
> Specifically here’s an example of what I would like to be able to write:  
> [http://www.pastie.org/1127920](http://www.pastie.org/1127920)
> 
> Yes, I can write the iterators, collects, merges and what else, but  
> nicer would be some kind of structured query syntax. Any ideas?

For the simple case one could do

class Hash  
def nested\_value? \*keys, val  
val.eql?( keys.inject(self) {|h,k| h.fetch(k) { return false } } )  
rescue return false  
end

def nested\_key? \*keys  
keys.inject(self) {|h,k| h.fetch(k) { return false } } rescue return  
false  
true  
end  
end

Note, you need 1.9\* for this - otherwise you need to manually  
distribute arguments.

Kind regards

robert
