From: "Eric I." Date: 2008-02-12T07:24:58+09:00 Subject: Re: Partial index hash search? On Feb 11, 3:47 pm, Serg Koren wrote: > What's the best way to find all occurances of a string in a hash's   > index? > > That is, > > x = { 'Hello' => 1, 'Goodbye' => 2, 'Hello there' => 3} > > How do I most efficiently get  1 and 3 to return on a search for   > 'Hello' in the index of the hash?  I know I can iterate over the   > index, but is there a better way? > > Thanks. Hi Serg, Here's one way to do it: x = { 'Hello' => 1, 'Goodbye' => 2, 'Hello there' => 3} result = x.keys.select { |k| k.include? "Hello" }.map { |k| x[k] } p result There's really no way to avoid iterating over the keys in the hash. In this case, Enumerable#select is doing that when it produces an array of the keys that contain "Hello". That array of keys is converted into an array of values by using Enumerable#map. Eric P.S. It looks like you replied to a posting for Ruby Quiz #156. Since this is unrelated to the Ruby Quiz, it would have been preferable to make a new post. ==== Are you interested in on-site Ruby training that uses well-designed, real-world, hands-on exercises? http://LearnRuby.com