Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use 'self' in Ruby

Tags:

ruby

This method:

  def format_stations_and_date
    from_station.titelize! if from_station.respond_to?(:titleize!)
    to_station.titleize! if to_station.respond_to?(:titleize!)
    if date.respond_to?(:to_date)
      date = date.to_date
    end
  end

Fails with this error when date is nil:

NoMethodError (You have a nil object when you didn't expect it!
The error occurred while evaluating nil.to_date):
  app/models/schedule.rb:87:in `format_stations_and_date'
  app/controllers/schedules_controller.rb:15:in `show'

However, if I change date = date.to_date to self.date = self.date.to_date, the method works correctly.

What's going on? In general, when do I have to write self?

Edit: It's not related to the question, but please note that there is no "titleize!" method.

like image 882
Tom Lehman Avatar asked Aug 09 '09 19:08

Tom Lehman


People also ask

What does self in Ruby mean?

self is a special variable that points to the object that "owns" the currently executing code. Ruby uses self everwhere: For instance variables: @myvar. For method and constant lookup. When defining methods, classes and modules.

Why do we use self in rails?

Because we don't have to use the class name for each method definition, making our code easier to change if we change the class. It also makes the code less noisy & better to read. That's why we do def self.

What is the use of @@ in Ruby?

The @ symbol before a variable tells Ruby that we are working with an instance variable, and @@ before a variable tells us we are working with a class variable. We use @ before a variable in instance methods within a class to tell Ruby to access that attribute (instance variable) of the instance.

What does self refer to in an instance method body?

the method self refers to the object it belongs to. Class definitions are objects too.


1 Answers

Whenever you want to invoke a setter method on self, you have to write self.foo = bar. If you just write foo = bar, the ruby parser recognizes that as a variable assignment and thinks of foo as a local variable from now on. For the parser to realize, that you want to invoke a setter method, and not assign a local variable, you have to write obj.foo = bar, so if the object is self, self.foo = bar

like image 190
sepp2k Avatar answered Oct 07 '22 00:10

sepp2k