1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Convoluted Constructions: a = 1, b = 2


Given the expression a = 1, b = 2, what will a and b be equal to? What will their types be? Why?

It's clear what this code intends to do, set the variables a and b to 1 and 2. So your first answer might be just that, but you'd be wrong. But first, let's take a look at why someone might make this mistake.

In C, the comma operator can be used to separate entire statements. A language lawyer would say that the comma operator creates a "sequence point." Everything before a sequence point is guaranteed to happen before everything after that sequence point. And of course the comma operator just separates the two statements. But this is not the case in Ruby.

Consider the following code.

a = 1, 2

What happens there? An array is created and assigned to the variable a. This doesn't even look valid, the Ruby idiom is to be square braces around Array literals. It's legal though, and it has to do with how the assignment operator works. The last variable on the left hand side will accept all remaining values from the comma separated list on the right hand side, and if there are more than one, they'll be stored in an Array. So what's happening here is the variable a is being assigned both numbers, and it's being stored in an Array.

Part of the confusion here is that Ruby doesn't have a comma operator, it has comma separated lists. You'll find these lists in various places, including Array literals, argument lists and method calls, assignments and in case statements.

So back to the original question: Given the expression a = 1, b = 2, what will a and b be equal to? We can see now that the comma here doesn't separate anything. Instead, you're assigning a comma separated list to a, and this list has two elements. So a will be an Array, and b will be a Fixnum. But what about their values? Well b's value is simple, it's just 2. But a's value depends on what the statement b = 2 evaluates to. Assignment statements always evaluate to their right side values (or "rvalues"), so this evaluates to 2. In short, a will be an Array of [1, 2] and b will be a Fixnum (or some other Numeric) equal to 2.

  1. About.com
  2. Technology
  3. Ruby
  4. Advanced Ruby
  5. Convoluted Constructions
  6. Convoluted Constructions: a = 1, b = 2

©2014 About.com. All rights reserved.