在Hash#fetch ruby​​中使用lambda作为默认值

时间:2019-02-06 08:58:25

标签: ruby ruby-hash

我正在阅读有信心的红宝石,并且正在尝试如何定义可重用的proc。从给出的示例中,我这样写:

DEFAULT_BLOCK = -> { 'block executed' }

answers = {}

answers.fetch(:x, &DEFAULT_BLOCK)

我期望它返回block executed,因为在哈希中找不到x,而是返回了wrong number of arguments (given 1, expected 0) (ArgumentError)。可能是什么问题?我没有给块一个参数。

3 个答案:

答案 0 :(得分:9)

您有,只是看不到:

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

answers = {}

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

Hash#fetch的块提供了一个参数,即您尚未找到的键。您可以在lambda中接受一个参数而忽略它,或者将其设为proc:

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

proc起作用的原因是,lambdas验证提供了正确数量的参数,而proc没有提供。 fetch方法使用一个参数(键)调用proc / lambda。

答案 1 :(得分:3)

Hash#fetch占用一个块时,密钥将传递到该块。但是您从proc创建的块不带任何块参数。将定义更改为:

DEFAULT_BLOCK = -> x { 'block executed' }

答案 2 :(得分:0)

    2.6.1 :014 > DEFAULT_BLOCK = -> { 'block executed' }
     => #<Proc:0x00005586f6ef9e58@(irb):14 (lambda)> 
    2.6.1 :015 > answers = {}
     => {} 
    2.6.1 :016 > ans = answers.fetch(:x) {DEFAULT_BLOCK}
     => #<Proc:0x00005586f6ef9e58@(irb):14 (lambda)> 
    2.6.1 :017 > ans.call
     => "block executed" 

    Actually we can pass default value for key so that if key not found in the hash it use this default value like,
    my_hash = {}
     => {} 
    2.6.1 :019 > my_hash[:key1] = 'val1'
     => "val1" 
    2.6.1 :020 > p my_hash
    {:key1=>"val1"}
     => {:key1=>"val1"} 
    2.6.1 :022 > my_hash.fetch(:key1)
     => "val1" 
    2.6.1 :023 > my_hash.fetch(:key2)
    KeyError (key not found: :key2)
    Did you mean?  :key1
    2.6.1 :024 > my_hash.fetch(:key2){'val2'}
     => "val2"