Using a lambda as a default in Hash#fetch ruby

You have, you just don't see it:

WHAT_AM_I_PASSING = ->(var) { var.inspect }

answers = {}

answers.fetch(:x, &WHAT_AM_I_PASSING)
# => ":x"

The block of Hash#fetch provides an argument, the key that you haven't found. You can either accept an argument in your lambda and just ignore it, or make it a proc:

DEFAULT_BLOCK = proc { 'block executed' }
answers.fetch(:x, &DEFAULT_BLOCK)
# => "block executed" 

The reason that a proc works, is that lambdas verify that the correct number of arguments were provided while procs don't. The fetch method is calling the proc/lambda with one argument (the key).


When Hash#fetch takes a block, the key is passed to the block. But your block created from a proc does not take any block argument. Change the definition to:

DEFAULT_BLOCK = -> x { 'block executed' }

Tags:

Ruby

Ruby Hash