ruby should I use self. or @

前端 未结 4 1539
小蘑菇
小蘑菇 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: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.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.

提交回复
热议问题