From: Todd Benson Date: 2008-02-13T08:24:43+09:00 Subject: Re: Partial index hash search? On Feb 11, 2008 4: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 I could only come up with an iterative solution also... h = Hash['Hello', 1, 'Goodbye', 2, 'Hello there', 3] a = h.select {|k, v| k=~/Hello/}.map {|v| v[1]} p a