akonsu
akonsu

Reputation: 29536

method= with multiple parameters

if I have a method with the equal sign at the end:

class A
  def property= name, value
    ...
  end
end

how do I invoke the method property= and pass arguments to it?

Upvotes: 2

Views: 273

Answers (2)

akonsu
akonsu

Reputation: 29536

here is what I ended up with (thanks to @LeeJarvis for his/her comment):

class A
  def property= value
    x, y = value
    p [x, y]
  end
end

A.new.property = 1, 2

Upvotes: 1

Chuck
Chuck

Reputation: 237010

Ruby already has a special setter syntax for key-value pairs. You can see it in use with Hash:

phone_numbers = { Bob: "555-555-1234", Francine: "555-555-5678"}
phone_numbers[:Jenny] = "555-867-5309"

To get this syntax for your own class, you just do

def []=(key, value)
  # set the value however you like
end 

Upvotes: 3

Related Questions