问题描述
在类定义中,这两种方法有什么区别?
In a class definition, what is the difference between these two methods?
def func(var)
...
end
def func=(var)
...
end
有没有,或者其中一个无效?
Is there any, or is one of them not valid?
推荐答案
解释一些关于 Ruby 中读写器也称为 getter/setter 方法的事情:
To explain some things about reader/writer AKA getter/setter methods in Ruby:
Ruby 不强制我们在 setter 的方法定义中使用 =
.我们可以选择该方法是否有一个.
Ruby doesn't force us to use =
in the method definition for a setter. We get to choose whether the method has one.
考虑一下:
class Foo
# automagically creates:
# .v
# .v=
attr_accessor :v
def initialize(v)
puts "inside initialize(#{ v })"
@v = v
end
def setter(v)
puts "inside setter(#{ v })"
@v = v
end
def setter=(v)
puts "inside setter=(#{ v })"
@v = v
end
end
f = Foo.new(1)
puts f.v
f.setter(2)
puts f.v
f.setter = 3
puts f.v
f.setter=(4)
puts f.v
f.v = 5
puts f.v
f.v=(6)
puts f.v
运行代码输出:
inside initialize(1)
1
inside setter(2)
2
inside setter=(3)
3
inside setter=(4)
4
5
6
=
只是方法名称中的另一个字母,因为 Ruby 足够聪明,知道它是否看到 f.setter = 3
它应该使用 setter=(v)
方法.
The =
is simply another letter in the method name because Ruby is smart enough to know if it sees f.setter = 3
it should use the setter=(v)
method.
Ruby 不强制使用 =
来设置变量,您可以在定义方法时决定它是否对您更有意义.我们使用 =
是惯用的,因为它有助于使 setter 看起来像一个赋值,消除了将所有 setter 命名为类似 set_v(v)
的冲动.
Ruby doesn't force using =
to set a variable, you can decide if it makes more sense to you when you define the method. It is idiomatic that we use =
because it helps make a setter look like an assignment, removing the urge to name all the setters something like set_v(v)
.
这篇关于def func(var) 和 def func=(var) 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!