1

I am a RoR developer and want to clarify some doubt about ruby variable assignment.

In ruby we have two ways for variable assignment.

str, arr, num = "Hi", [1, 2], 3

and

str = "Hi"
arr = [1, 2]
num = 3

I know that the first way will go slower than second way but, I want to know that as per ruby language, which way is preferable and performance reliable?

2 Answers 2

4

"Writing Efficient Ruby Code" by Dr. Stefan Kaes has this to say about parallel assignment (your first example):

Like any other Ruby expression, a value needs to be returned from a parallel assignment. The value returned by a parallel assignment is the value of the expression on the right-hand side of the assignment. This means Ruby needs to create an array if the right-hand side is a list of expressions:

$ irb
>> a,b = 1,2
=> [1, 2]

Of course, if the assignment isn’t the last statement of a method, the created array becomes garbage immediately. It’s therefore advisable to avoid the use of parallel assignment in performance-critical code sections.

Dr. Kaes goes on to speculate that Ruby 1.9 may change the semantics of parallel assignments to always return true for performance reasons.

To my eye, parallel assignment aids neither clarity nor maintainability, so, performance reasons aside, I would avoid it as a matter of course.

1
  • There are circumstances where parallel assignment aids clarity. One is swapping: a, b = b, a. Another is a function with multiple return values: a, b = somefunc (although multiple return values can frequently be better handled as an instance of a distinct class). Commented Sep 1, 2012 at 21:59
0

Second option is preferable in most of the cases. However first case is more readable in some situations.

If you have common kind of variables or an array you can use first case. Example:

arr1, arr2, arr3 ... arr20 = 1, 2, 3 ... 20

In this case using 1 line of code is more preferable then using 20 different statements. Code is more readable.

If you are going to use parallel assignments you need to take care of assignment flow

Not the answer you're looking for? Browse other questions tagged or ask your own question.