Friday, March 8, 2013

When to Use "self" Keyword Explicitly

In Ruby, when you are defining an instance method, the keyword "self" can be used to refer to the current object.

class Name < String
  def write_name_in_capital_letter
    self.upcase
  end
end
name = Name.new('david')
name.write_name_in_capital_letter
=> "DAVID"

In the example above, you can remove the self keyword and the method still works. That's because when you call a method without an explicit receiving object, the method message is implicitly sent to "self". In this case, upcase is sent to "self".

class Name < String
  def write_name_in_capital_letter
    upcase
  end
end
name = Name.new('david')
name.write_name_in_capital_letter
=> "DAVID"
This is just a Ruby's idiom to save programmers' work. However, abusing this feature may lead to unexpected result. There are two situation where "self" is needed to get desirable result. The first situation is when you attempt to call the method "class".

class Name < String
  def show_my_class_name
    puts class.name
  end
end
It actually gives the following error.

SyntaxError: (irb):49: syntax error, unexpected '.'
puts class.name
Because the Ruby interpreter thinks of "class" as the class keyword instead the class method.

Another situation is when you attempt to call the setter method on an instance variable.

class Name < String
  attr_accessor :an_attr

  def change_attr
     an_attr = 'hohoho'
  end
end
n = Name.new
n.an_attr = 'hahaha'
n.change_attr
n.an_attr
 => "hahaha"
We can see no error is thrown, but "an_attr" is not changed at all. That's because the "an_attr=" in method change_attr is not interpreted as the setter method of "an_attr". Instead, it is an assignment of local variable. Because if Ruby interpreter takes it as the setter method, there will be no way left for you to define a local variable named "an_attr".

So in these two situations you need to use "self" explicitly.

References
http://www.jimmycuadra.com/posts/self-in-ruby

1 comment:

  1. Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck!!

    PIC Bonus Singapore

    ReplyDelete