Ruby Quiz (Easy) #6

question mark


what is the output of those 3 tricky puts?



z + 2 = 3
z +2 = 3

First puts

You might have expected 1 as the answer. However, x = y or z actually evaluates as if it were (x = y) or z, thus assigning y to x.

The reason is because the = operator has as higher precedence than the or operator, as per the Ruby operator precedence table.

Second puts

In the second puts, the space between the + and the 2 makes it clear that the + is the + operator, and not a positive sign for the following value. Thus, 1 + 2 = 3

Third puts

For that one, the only difference with the “second puts” is the removal of the white space between the positive sign and the 2. This time, the + might actually be a positive sign for the following value. However, since the parser saw an assignment for z in the same scope previously, it is thus treated as a variable, and not as a method (even if the z method has been defined afterwards). So again, 1 + 2 = 3

If you want to refer to the method, adding the parentheses would force it to, like so: z(+2)

And if the z would have been defined only as a method before using it, then the z in z + 2 would have caused an error: ArgumentError: wrong number of arguments (0 for 1). But z +2 would have called the z method without complaining.


  1. The result of the first puts is the int 1. You have typo under: Solution:This is the output:

  2. @gene_tani: Using Ruby 1.8.6, the result of the first puts is “false”.And thanks for the heads up on the typo, it is now fixed.

Got a comment?

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: