Jinn
Jinn

Reputation: 111

Ruby trying to push to hash with (**parameter)

I'm trying to multiple[sic] parameters to a hash and getting this error:

`method': wrong number of arguments (3 for 0) (ArgumentError)

Could someone tell me how I could accomplish this/what I am doing wrong?

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])

Upvotes: 2

Views: 86

Answers (1)

Mulan
Mulan

Reputation: 135227

You might want to consider more idiomatic use of Ruby

class MyClass
  def initialize
    @variable = {}
  end

  def method hash
    @variable.merge! hash
  end
end

Then use it like this

foo = MyClass.new
foo.method a: 1, b: 2

The last line is sugared-up Ruby for

foo.method({:a => 1, :b => 2})

Hash#merge! docs

Upvotes: 4

Related Questions