问题
Hello dear stackoverflowers :)
I came from Java and have one doubt about the syntax of getters (if it's really just a syntax issue).
In java you would have a setter like
private void setName(value) {
variableName = value;
}
who would take value as an argument and change the instance variable inside it.
In ruby, when I explicitly define a setter (due to constraint reasons), I need to use set_name=(value) or if I use the syntax set_name(value) would be the same? In other words, the = in the end of the method name does anything else or it's just syntax (like ! and ?).
Like this:
def set_name=(value)
@name = value
end
Or this:
def set_name(value)
@name = value
end
Thanks in advance for the attention.
Alex
回答1:
The trailing =
in the method name identifies the method as a setter/mutator method. When you say this in Ruby:
o.p = v
You're really saying:
o.send(:p=, v)
so o.p = v
is just a fancy way of calling the p=
method in o
. That's why things like this:
's'.pancakes = 11
gives you a NoMethodError
exception that complains about 's'
not having a pancakes=
method: Strings don't (unfortunately) have pancakes=
methods.
In your case, you wouldn't use set_name
at all, you'd have a name=
method:
def name=(value)
@name = value
end
and possibly a name
method as an accessor/getter:
def name
@name
end
回答2:
The most idiomatic approach in Ruby is to do
def name=(value)
@name = value
end
or better yet,
attr_writer :name
回答3:
I need to use set_name=(value) or if I use the syntax set_name(value) would be the same?
class Dog
attr_reader :name
def initialize(name)
@name = name
end
def name1=(str)
@name = str
end
def name2(str)
@name = str
end
end
d = Dog.new("Rover")
puts d.name #=>Rover
d.name1 = "Ruthie"
puts d.name #=>Ruthie
d.name2("John")
puts d.name #=>John
d.name2 = "Roger"
--output:--
1.rb:23:in `<main>': undefined method `name2=' for #<Dog:0x00000100907030 @name="John"> (NoMethodError)
For setters, the name of the method includes the '=' sign. But ruby also allows you to use syntactic sugar with method names that end in '=':
obj.setter_name = value
is equivalent to:
obj.setter_name=(value)
来源:https://stackoverflow.com/questions/24004582/ruby-setter-method-syntax-method-value-comparison-to-java