ruby should I use self. or @

前端 未结 4 1503
小蘑菇
小蘑菇 2021-01-30 17:57

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

相关标签:
4条回答
  • 2021-01-30 18:18

    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.

    0 讨论(0)
  • 2021-01-30 18:25

    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).

    0 讨论(0)
  • 2021-01-30 18:28

    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.

    0 讨论(0)
  • 2021-01-30 18:40

    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 讨论(0)
提交回复
热议问题