From: Serg Koren Date: 2008-02-12T08:31:05+09:00 Subject: Re: Partial index hash search? oops i took the easy way and replied. sorry. Thanks for the help/explanation. I was hoping there was a shorter/ more efficient way than iterating maybe a nested hash of some sort. Guess I'll settle for what we have. Thanks much. On Feb 11, 2008, at 5:24 PM, Eric I. wrote: > 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 >