From: barjunk Date: 2007-07-12T05:45:02+09:00 Subject: Re: Returning part of a hash On Jul 11, 12:28 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. > > Mike B. This is backwards, but works: ["key1","key2","key3","key2"].each {|item| hash.delete_if { | key,value| key == item} } This would get rid of the keys I don't want. I could probably do something like: (hash.keys - ["keys", "I", "want"]).each {|item| hash.delete_if { | key,value| key == item} } The only bummer is that directly modifies the hash...but that can be fixed too. I'm still new at this...is there a more succinct way? Mike B.