How to use Hash#to_proc in Ruby?
2 mins readHash#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.
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.
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.
Rails console using ActiveRecord::AttributeMethods#attributes method.
Before Ruby 2.3.0 you would need to do something like that:
Happy coding!