danielewski.dev

Hash#to_proc in Ruby

REWARDS = { 'gold' => 50000, 'silver' => 20000, 'bronze' => 13000 }
medals = %w[gold gold silver silver bronze bronze bronze]

In order to sum the money won in total we could use Enumerable#inject:

cash = medals.inject(0) { |sum, i| sum += REWARDS[i]; sum }
# => 179000

Or we can simply use Hash#to_proc.

Hash#to_proc will, of course, return a proc. This proc will accept a key as a parameter and return the corresponding value.

REWARDS.to_proc # => #<Proc:0x007ffba2126358>
REWARDS.to_proc.call('gold') # => 50000

Knowing this, we can pass the hash as a parameter of map with a & in front of it to tell Ruby to use the proc as a block.

medals.map(&REWARDS)
# => [50000, 50000, 20000, 20000, 13000, 13000, 13000]

medals.map(&REWARDS).sum
# => 179000

Doing:

medals.map(&REWARDS)
# => [50000, 50000, 20000, 20000, 13000, 13000, 13000]

is equivalent to:

medals.map { |medal| REWARDS[medal] }
# => [50000, 50000, 20000, 20000, 13000, 13000, 13000]

A very simple use case of Hash#to_proc.