This post originated from an RSS feed registered with Ruby Buzz
by Matthew Bass.
Original Post: Picking values from Ruby hashes
Feed Title: Pelargir
Feed URL: http://feeds.feedburner.com/pelargir/
Feed Description: Musings on software and life from Matthew Bass. Regular posts on new web products, tips and tricks, etc.
Want to pick a certain set of key/value pairs from a Ruby hash? You might do this:
hash = {:foo => "bar", :bar => "baz", :baz => "boo"}
hash.select { |k,v| [:foo, :bar].include?(k) }
# returns [[:foo, "bar"], [:bar, "baz"]]
Kind of messy. We can do better by reopening the Hash class this way:
class Hash
def pick(*values)
select { |k,v| values.include?(k) [...]