From: Trans Date: 2008-04-13T19:04:23+09:00 Subject: Re: Hash#slice On Apr 13, 4:58 am, "Robert Dober" wrote: > On Sun, Apr 13, 2008 at 2:51 AM, ara.t.howard wrote: > > > On Apr 12, 2008, at 5:12 PM, Trans wrote: > > > > Let see.... Facets: > > > > class Hash > > > > # Returns a new hash with only the given keys. > > > > def slice(*keep_keys) > > > h = {} > > > keep_keys.each do |key| > > > h[key] = fetch(key) > > > end > > > h > > > end > > > > # Replaces hash with a new hash having only the given keys. > > > # This return the hash of keys removed. > > > > def slice!(*keep_keys) > > > removed = except(*keep_keys) > > > replace(slice(*keep_keys)) > > > removed > > > end > > > > end > > > okay, you should add the block form ;-) > > > headers.slice{|k,| k =~ %r/^HTTP_/} > > > handy..... > > > cheers. > > > a @http://codeforpeople.com/ > > -- > > we can deny everything, except that we have the possibility of being > > better. simply reflect on that. > > h.h. the 14th dalai lama > > Hmm maybe it is a more consistent approach not to add a block to slice. > > FWIAC, I use hselect, kselect and vselect, the simplified code > goes like this (1) of course > def kselect &blk > hselect{ |k,| blk.call(k) } > end > > def vselect &blk > hselect{ |_,v| blk.call(v) } > end > def hselect &blk > #almost Tom's code of course > end Why not? hash.keys.select hash.values.select > You might write > h.slice(*[*1..10]){|k,v| whatever k, v } > which indeed I like > > I would write > h.slice(*[*1..10]).hselect{|k,v| whatever k, v} > which indeed I like less, *but* I dislike the inconsistency of #select now. > > The ideal solution might be to add a block to Enumerator#select too, > what about that? Hmm... I don't understand Enumerator#select comes from Enumerable#select and already takes a block. T.