ruby using the "&:methodname" shortcut from array.map(&:methodname) for hash key strings rather than methodname ruby using the "&:methodname" shortcut from array.map(&:methodname) for hash key strings rather than methodname ruby ruby

ruby using the "&:methodname" shortcut from array.map(&:methodname) for hash key strings rather than methodname


You can do this with a lambda:

extract_keyname = ->(h) { h[:keyname] }ary_of_hashes.map(&extract_keyname)

This tends to be more useful if the block's logic is more complicated than simply extracting a value from a Hash. Also, attaching names to your bits of logic can help clarify what a chain of Enumerable method calls is trying to do.

You can also have a lambda which returns a lambda if you're doing this multiple times:

extract = ->(k) { ->(h) { h[k] } }ary_of_hashes.map(&extract[:keyname])ary_of_hashes.map(&extract[:other_key])

or a lambda building method:

def extract(k)  ->(h) { h[k] }endary_of_hashes.map(&extract(:keyname))ary_of_hashes.map(&extract(:other_key))


& before a statement in a line of ruby is a shortcut of calling to_proc.

On a symbol to_proc looks for the method on the "context" and calls uses that as reference.

also:


If you are working with ruby on rails, you can use the Enumerable#pluck method, which is implemented by ActiveSupport.This will allow you to do the following:

array_of_hashes = [{a: 1, b: 2}, {a: 3,b: 4}, {a: 5, b: 6}]=> [{:a=>1, :b=>2}, {:a=>3, :b=>4}, {:a=>5, :b=>6}]array_of_hashes.pluck(:b)=> [2, 4, 6]

See the documentation here: https://www.rubydoc.info/gems/activesupport/5.0.0/Enumerable:pluck