Reputation: 841
To make a setter and a getter for Dessert
class, I made the following code:
class Dessert
def initialize(name,calories)
@name=name
@calories=calories
end
def name
@name
end
def name=(names)
@name=names
end
def calories
@calories
end
def calories=(calory)
@calories=calory
end
end
d=Dessert.new("Salad",1200)
puts d.name("Khoresht")
puts d.calories(1600)
puts d.name()
puts d.calories()
The setter and getter must have the same name, and the compiler recognizes them by their signature. But here, I face the error:
`name': wrong number of arguments (1 for 0) (ArgumentError)
for the method name (the setter).
Why does it happen?
Upvotes: 0
Views: 435
Reputation: 8821
you should change d.name("Khoresht")
to d.name=("Khoresht")
d=Dessert.new("Salad",1200)
d.name = "Khoresht" # use setter method, equal to d.name=("Khoresht")
d.calories = 1600
puts d.name
puts d.calories
The setter and getter have different name, in your codes, setter method name contains a =
.
Upvotes: 2
Reputation: 106832
pangpang already answered your question. I just want to mention that it is uncommon in Ruby to define getter and setter methods.
Instead a common way is to use attr_accessor
to declare getter and setter methods. The following example is equivalent to your code:
class Dessert
attr_accessor :name, :calories
def initialize(name, calories)
@name = name
@calories = calories
end
end
And other option might be to inherit from Struct
. The following example has the same behaviour than your code:
class Dessert < Struct.new(:name, :calories)
end
Upvotes: 2