Nov 29

Somebody left a comment regarding to my Ruby Gotcha #1 post:

Since you posted this a while ago, you may have since learned of instance variables, which are preceeded by an ‘@’. If not, well here is the proper way to write your setter.

class Foo
  attr_accessor :bar
  def setNewBar=(newBar)
    @bar = newBar
  end
end

Whoever made this comment missed the point here. Yes, the above solution will work. But it’ll only work in this simple case. Whatever language you are using, it’s always a good OO practice to use accessor instead of instance variable directly. This is especially true in a language like Ruby where the instance variable is always private (although it’s very hard to demonstrate this behaviour). In our example, if you have a class that extends Foo, the subclass shouldn’t use ‘@’ to access the instance variable. Instead, it must use the attribute accessor. Then we will end up with the same problem. The correct way to deal with it is to preceed the attribute accessor with ’self’.

The more I learn Ruby the more interesting I find it is. These gotchas is also part of what makes it interesting. Watch out for more posts about them.

Leave a Reply

preload preload preload