When to use me in 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 

This error fails if 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 happening? In general, when do I need to write self ?

Edit: This is not a question, but note that there is no "titleize!". Method.

+9
ruby
Aug 09 '09 at 19:31
source share
2 answers

Whenever you want to call the setter method for yourself, you need to write self.foo = bar. If you simply write foo = bar, the ruby ​​marker recognizes this as a variable assignment and now treats foo as a local variable. To make the analyzer understand that you want to call the setter method and not assign a local variable, you need to write obj.foo = bar, so if the object is self, self.foo = bar

+42
Aug 09 '09 at 19:35
source share

You deviate between the instance method name and the local variable using self (allowed to have the same name in the same scope). In other words, there will be resolution of the method name only if there is no local or block variable with the same name in the region. Here:

 class Foo attr_accessor :boo def do_boo boo = 123 puts "Locvar: #{boo} Method: #{self.boo}" end end Foo.new.do_boo 

Here's why: imagine you have a module that implements a method. This method assigns it the internal local variable "foo", which is used for some calculations. If you skip the "self" part, the method will make a call to the "foo =" method on an object whose class includes a module that was not the author’s intention and can be completely disastrous.

 class Foo def bar=(new_value_of_bar) set_off_nukes(new_value_of_bar / 3) end end module InnocentModule # written by a different author elsewhere def do_useful_stuff ... bar = Math.sin(something) # we're dead end end Foo.send(:include, InnocentModule) 

Another important part in which you should use self is to call the Object # class method, because simply saying β€œclass” means the class keyword for Ruby.

+7
Aug 10 '09 at 17:59
source share



All Articles