From: Trans Date: 2007-07-13T03:41:45+09:00 Subject: Re: Returning part of a hash On Jul 11, 4:30 pm, barjunk wrote: > I have hash that has about 20 keys. I'd like to create a new variable > with just three of those keys. Example: > > hash = { "key1" => "value1", > "key2" => "value2", > ... > "key20" => "value20" } > > And a function like: > newhash = hash.slice("key2","key5","key7") > > Which creates: > > newhash = { "key2" => "value1", > "key5" => "value5", > "key7" => "value7" } > > hash.select {|key, value| key == "key1" } > > I could do the above multiple times, but this returns an array not the > hash pair. > > Thanks for any help. class Hash # Hash intersection. Two hashes intersect # when their pairs are equal. # # {:a=>1,:b=>2} & {:a=>1,:c=>3} #=> {:a=>1} # # A hash can also be intersected with an array # to intersect by keys only. # # {:a=>1,:b=>2} & [:a,:c] #=> {:a=>1} # # The later form is similar to #pairs_at. This differs only # in that #pairs_at will return a nil value for a key # not in the hash, but #& will not. def &(other) case other when Array k = (keys & other) Hash[*(k.zip(values_at(*k)).flatten)] else Hash.new[*(to_a & other.to_a).flatten] end end end T. --- http://facets.rubyforge.org