When to use 'self' in Ruby

ruby

Solution

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

Problem

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.

Original source

Related problems