开发者

ruby should I use self. or @

Here is my ruby开发者_开发技巧 code

class Demo
  attr_accessor :lines

  def initialize(lines)
    self.lines = lines
  end
end

In the above code I could have used

    @lines = lines

Mostly I see people using @ in initialize method. Is there a preferred way of doing among these two and why?


When you use @lines, you are accessing the instance variable itself. self.lines actually goes through the lines method of the class; likewise, self.lines = x goes through the lines= method. So use @ when you want to access the variable directly, and self. when you want to access via the method.

To directly answer your question, normally you want to set the instance variables directly in your initialize method, but it depends on your use-case.


self.lines is a method, @lines is the instance variable. In your constructor you'll want to use self.lines I would argue, but that's up for debate. It's just a stylistic difference, really. If you want a deeper discussion of direct vs. indirect variable access, read the chapter from Kent Beck's Smalltalk Best Practice Patterns.


The main difference would be if you redefined lines= to do something other than @lines = lines.

For example, you could add validation to the attribute (for example, raising if lines is empty).


I think there is a little difference that has not be mentioned yet. The instance variable @lines can only be accessed within the class.

class Foo
 def initialize
   @lines = 1
 end
end

foo = Foo.new
foo.lines
>> NoMethodError: undefined method `lines' for #<Foo:0x1017cfb80 @lines=0>
foo.send(:lines)
>> 1

If you define attr_accessor :lines all instances of that class can access the lines variable:

class Foo
 attr_accessor :lines
 def initialize
   self.lines = 1
 end
end

foo = Foo.new
foo.lines
>> 1

If you want your variable to be accessible for all instances you should use attr_accessor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜