From: Florian Frank Date: 2007-01-23T22:58:55+09:00 Subject: Re: Hash pairs at? Joel VanderWerf wrote: > Alex LeDonne wrote: >> Maybe I'm late to the party, but instead of select_pair, I'd name the >> method slice, analagous to Array#slice. > > Looks like the rails crowd has beaten us to it: > > http://dev.rubyonrails.org/changeset/5726 > > It might be in facets, too. > > Seems like a good name for a good method. > I called it 'extract' and use this: module HashInclusion # Extract a hash out of this hash, that only contains key-value pairs # matching _patterns_ and return it. _patterns_ can be for example /^foo/ # to extract 'foobar' and 'foobaz' or 'foo'/:foo to extract 'foo'. def extract(*patterns) patterns.map! { |pat| pat.respond_to?(:match) ? pat : pat.to_s } result = default_proc ? self.class.new(&default_proc) : self.class.new(default) each { |k, v| result[k] = v if patterns.any? { |pat| pat === k.to_s } } result end end class ::Hash include HashInclusion end The duck typing is a bit fishy, but it's possible to add pattern objects, that implement #=== and #match this way. Coincidently this is the case for Regex instances. It's also interesting, that it's quite difficult to create an empty "copy" of a given hash in Ruby, without duping and clearing it. -- Florian Frank