我尝试将多个[原文如此]参数传递给哈希并收到此错误:
`method': wrong number of arguments (3 for 0) (ArgumentError)
有人可以告诉我如何完成这个/我做错了什么吗?
class MyClass
attr_accessor :variable
def initialize
@variable = {}
end
def method(**parameter)
parameter.each {|k,v| @variable[k] = v}
end
end
new_class = MyClass.new
p new_class.method(["key", 1],["house", 2],["key", 3])
最佳答案
您可能需要考虑更惯用的 Ruby 用法
class MyClass
def initialize
@variable = {}
end
def method hash
@variable.merge! hash
end
end
然后像这样使用它
foo = MyClass.new
foo.method a: 1, b: 2
最后一行是加糖的 Ruby
foo.method({:a => 1, :b => 2})
关于Ruby 尝试使用(**参数)推送哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26644769/