From: Craig Demyanovich Date: 2007-07-12T06:27:00+09:00 Subject: Re: Returning part of a hash ------=_Part_8588_6185560.1184189213790 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 7/11/07, Ezra Zygmuntowicz wrote: > > > On Jul 11, 2007, at 1: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. > > > > Mike B. > > > Hey Mike- > > Here are two handy methods for doing what you want: > > class Hash > # lets through the keys in the argument > # >> {:one => 1, :two => 2, :three => 3}.pass(:one) > # => {:one=>1} > def pass(*keys) > self.reject { |k,v| ! keys.include?(k) } > end > > # blocks the keys in the arguments > # >> {:one => 1, :two => 2, :three => 3}.block(:one) > # => {:two=>2, :three=>3} > def block(*keys) > self.reject { |k,v| keys.include?(k) } > end > > end Ezra, Since you're adding the #pass and #block methods to Hash and Hash already has a #keys method, is there a conflict between the *keys parameter to #pass and #block and the #keys method on Hash? Thanks, Craig ------=_Part_8588_6185560.1184189213790--