Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

When to use `self.foo` instead of `foo` in Ruby methods

This is not specific for Rails - I am just using Rails as an example.

I have a model in Rails:

class Item < ActiveRecord::Base

  def hello
    puts "Hello, #{self.name}"
  end
end

(Let's assume that the Item model (class) has a method called name.) When do I need to use self.name and when can I just use name (e.g., #{name})?

question from:https://stackoverflow.com/questions/4699687/when-to-use-self-foo-instead-of-foo-in-ruby-methods

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. It is idiomatic to prefer to omit self. when invoking methods; it is generally never needed.

  2. You must use self.foo = xxx when calling a setter method, instead of foo = xxx, so that Ruby realizes that you are not trying create a new local variable.

    • Similarly, in the unlikely event that you have an existing local variable do_something with the same name as a method, you must use self.do_something to invoke the method, as just do_something will end up reading the variable.
  3. You cannot use self.foo(...) to call a private method; you must instead call just foo(...).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...