Ruby 尝试使用(**参数)推送哈希

标签 ruby

我尝试将多个[原文如此]参数传递给哈希并收到此错误:

`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})

Hash#merge! docs

关于Ruby 尝试使用(**参数)推送哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26644769/

相关文章:

ruby - ruby 中的数据结构只存储唯一元素?

ruby - 需要 nokogiri : Load Error

ruby - Rails update_all 与 hstore

ruby - 我如何在 Clojure 中编写 Ruby 的 each_cons?

ruby-on-rails - 使用 session 变量设置数据库连接

ruby - 如何使 "require"在 Ruby 中静默失败

ruby-on-rails - has_many 同时尊重 factory_girl 中的构建策略

ruby - 如何在 Mac OS X 上不使用 sudo 安装 gems

ruby-on-rails - Rails 删除方法不起作用

ruby-on-rails - Ruby 和 Cucumber - 这是什么意思? "([^"]*)"$/