pahanix & IT

yet another passionate programmer

3 notes &

How a little comma in ruby code can be a pain in the neck

Let assume that you transform a hash

{
  :a => 1,
  :b => 2
}

into local variables somewhere in your code and forget to remove a little comma after one line

a = 1,
b = 2

You still have a valid ruby code but it produces something unexpected!

a # => [1,2]
b # => 2

Why? Because of the comma ruby uses multiple assignment operator to assign values. Let write the code into one line to clarify what happens here.

a = 1, b = 2
a = 1, (b = 2)
a = 1, 2
a # => [1,2]

Next time you see an unexpected array, search for a comma!

Filed under ruby comma multiple assignment parallel assignment

  1. pahanix posted this