2

I'm very used to using the ruby & shorthand for array methods, ex:

a = [1, 3, 4]
a.map(&:to_f)
# => [1.0, 3.0, 4.0]

instead of a.map {|x| x.to_f }

Is there an equivalent for an array of hashes? For ex:

a = [{'first' => 1, 'second' => 4}, {'first' => 5, 'second' => 6}]
a.map(&:'first')
# => [1, 5]

Something like this? That is a shorthand over a.map { |x| x['first'] } ?

This would be especially useful when I have large arrays of many nested hashes to drill down into.

hammer96
  • 55
  • 2
  • `:'first' == :first` -- it's absolute the same :) – mechnicov Oct 06 '22 at 22:08
  • This is pretty similar to [**using the "&:methodname" shortcut from array.map(&:methodname) for hash key strings rather than methodname**](https://stackoverflow.com/q/20179636/479863), isn't it? – mu is too short Oct 06 '22 at 22:58

1 Answers1

2

Numbered parameters were introduced in ruby 2.7 which makes the following a nice short hand way to accomplish what you want.

a = [{ "first" => 1, "second" => 4 }, { "first" => 5, "second" => 6 }]
a.map {_1['first']}
nPn
  • 16,254
  • 9
  • 35
  • 58