How to use Hash#to_proc in Ruby?

Hash#to_proc has been introduced in Ruby 2.3.0 release. I really like this method. It reminds obtaining a value from a HashMap in Clojure.


=> ({:a 1} :a)
1

We simply “call” hash-map with :a keyword as a parameter to get the :a’s keyword value. Thanks to Hash#to_proc method, in Ruby now we can do almost the same thing.


irb(main):001:0> {a: 1}.to_proc.call(:a)
=> 1

Of course for getting a value from hash it’s much easier to use #[] but sometimes #to_proc is just as useful and allows you to simplify the code.

Here’s how I use it in wildlife

Let’s say I’m not sure what the name of the key is, but what I really need to know is the value.


irb(main):001:0> ENV.keys.grep(/shell/i).map(&ENV.to_hash)
=> ["/usr/local/opt/bash/bin/bash", "bash"]
irb(main):002:0> ENV.keys.grep(/shell/i)
=> ["SHELL", "RBENV_SHELL"]

Rails console using ActiveRecord::AttributeMethods#attributes method.


[1] (main)> attrs = User.last.attributes
[2] (main)> attrs.keys.grep(/name/).map(&attrs)
=> ["Radek", "Molenda"]

Before Ruby 2.3.0 you would need to do something like that:


[3] (main)> keys = attrs.keys.grep(/name/)
=> ["first_name", "last_name"]
[4] (main)> attrs.values_at(*keys)
=> ["Radek", "Molenda"]

Happy coding!