This has been undermining me for a while. Itโs not difficult, but I donโt know why there is no easy way to do it already, and Iโm sure there are, and I donโt see it.
I just want to take a hash, for example:
cars = {:bob => 'Pontiac', :fred => 'Chrysler', :lisa => 'Cadillac', :mary => 'Jaguar'}
and do something like
cars[:bob, :lisa]
and get
{:bob => 'Pontiac', :lisa => 'Cadillac'}
I did this, which works great:
class Hash def pick(*keys) Hash[select { |k, v| keys.include?(k) }] end end ruby-1.8.7-p249 :008 > cars.pick(:bob, :lisa) => {:bob=>"Pontiac", :lisa=>"Cadillac"}
There obviously are two million easy ways to do this, but I wonder if there is something that I missed, or a good non-obvious reason, is this not a standard and normal thing? Without this, I end up using something like:
chosen_cars = {:bob => cars[:bob], :lisa => cars[:lisa]}
which is not the end of the world, but he is not very beautiful. It seems like this should be part of a regular dictionary. What am I missing here?
(related questions include the following: Ruby Hash whitelist filter ) (this blog post has exactly the same result as me, but again, why is this not built-in? http://matthewbass.com/2008/06/ 26 / picking-values-from-ruby-hashes / )
update:
I am using Rails, which has ActiveSupport :: CoreExtensions :: Hash :: Slice, which works exactly the way I want, so the problem is solved, but still ... maybe someone will find their answer here :)