Sep 10
As I’m slowly gradually learning Ruby, I find a number of stuff that can categorized as gotchas. I would like to record them here for future reference. The following is one of them. I personally think it’s pretty big.
Normally, methods within a class can invoke other methods in the same class and its superclasses in functional form (that is, with an implicit receiver of self). However, this doesn’t work with attribute writers. Ruby sees the assignment and decides that the name on the left must be a local variable, not a method call to an attribute writer.
class Foo
attr_accessor :bar
def setNewBar=(newBar)
bar = newBar
end
end
foo = Foo.new
foo.bar = 10
foo.setNewBar = 100
foo.bar -> 10
Ruby stored the new value in a local variable of method setNewBar= instead of using the attribute writer. I can see this causing some nasty bugs.
More on Ruby Gotchas to follow.
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