Ruby Quiz (Intermediate) #6

question mark

Question

What would be the output of this code snippet?

 

Solution

The output is “nil”. Here is the reason why, taken from Programming Ruby 2nd edition (p. 86):

[W]ritable attributes have a hidden gotcha. 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.

As such, the attribute var has never been assigned any value, and thus at line 9, its value is still “nil”. More appropriately, self.var = 45 would have assigned the value 45 to the attribute var.

Advertisements

One comment

  1. Oh. I didn't know about this gotcha. Thanks!

Got a comment?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: