ruby should I use self. or @

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

提交回复
热议问题