这是一些代码:
class Person
def initialize(age)
@age = age
end
def age
@age
end
def age_difference_with(other_person)
(self.age - other_person.age).abs
end
protected :age
end
Run Code Online (Sandbox Code Playgroud)
我想知道的是两者的区别@age,并self.age在age_difference_with方法.
在ruby中,我经常发现自己编写以下内容:
class Foo
def initialize(bar, baz)
@bar = bar
@baz = baz
end
<< more stuff >>
end
Run Code Online (Sandbox Code Playgroud)
甚至
class Foo
attr_accessor :bar, :baz
def initialize(bar, baz)
@bar = bar
@baz = baz
end
<< more stuff >>
end
Run Code Online (Sandbox Code Playgroud)
我总是希望尽可能地减少样板 - 所以有没有更惯用的方式在ruby中创建对象?