如何在与键对应的散列上产生一个值,或者默认为nil

问题描述 投票:-1回答:1

在Ruby散列的初学者练习中遇到了一些障碍。我有以下问题要解决:

创建一个带有两个参数的方法调用read_from_hash。第一个参数是哈希,第二个参数是键。一起使用,它们将在对应于键的哈希值上生成一个值,或者默认为nil。结合使用这两个参数即可做到这一点。

这是我的代码:

def read_from_hash(hash, key)
  hash = {key => "value"}
  hash(key)
end

这里是错误:

     Failure/Error: expect(read_from_hash({name: 'Steve'}, :name)).to eq('Steve')

     ArgumentError:
       wrong number of arguments (given 1, expected 0)
ruby
1个回答
2
投票

您想要的只是:

def read_from_hash(hash, key)
  hash[key]
end
h = {a: 1, b: 2}

read_from_hash(h, :a)
#=> 1
read_from_hash(h, :c)
#=> nil

或者您的示例:

read_from_hash({name: 'Steve'}, :name)
#=> 'Steve'

您当前的代码:

hash = {key => "value"} 

创建一个新的hash变量,覆盖通过参数传递的变量,而在这里:

hash(key) 

您正在尝试使用规则括号key而不是括号(),使用键[]访问元素的值。因此,实际发生的是您正在调用#hash方法,并将key变量作为参数传递给它。

© www.soinside.com 2019 - 2024. All rights reserved.