我在Ruby中的一次哈希初学者练习中遇到了一些障碍。我有以下问题需要解决:
创建一个方法调用read_from_hash,该方法接受两个参数。第一个参数是散列,第二个参数是密钥。如果一起使用,它们将在对应于密钥的散列上生成一个值,或者默认情况下为零。将这两个参数结合使用即可做到这一点。
这是我的代码:
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)
您想要的只是:
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
变量,覆盖通过params传入的变量,而这里:
hash(key)
您正试图使用正则括号()
而不是括号[]
来访问关键字为key
的元素的值。因此,实际发生的情况是,您正在调用一个#hash
方法,并将key
变量作为参数传递给它。