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
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.
Julik Aug 10 '09 at 17:59 2009-08-10 17:59
source share