pankajdoharey
pankajdoharey

Reputation: 1572

What is this in Ruby, and why does it exist?

Is it an array? What is its structure and usage? Why does it exist in Ruby?

>> Z =  x=1 , y =2 , a =3 , b=4


=> [1,2,3,4]

Why does this array support initialization? Can it be of any potential use? Why did the designers of Ruby support such an esoteric array declaration?

Upvotes: 2

Views: 274

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

It's one of those things that can be done but probably shouldn't because it hides what its intention is behind a thin veil of cleverness, making it harder to maintain.

Basically, it's assigning an array to Z while initializing the other variables.

Z =  x=1 , y =2 , a =3 , b=4 #=> [1, 2, 3, 4]
Z #=> [1, 2, 3, 4]
x #=> 1

Personally, in a code review I'd ask the programmer to write it one of these ways:

Z = [1, 2, 3, 4]

x, y, a, b = *Z

or

(x, y, a, b) = Z

Upvotes: 5

Michelle Tilley
Michelle Tilley

Reputation: 159095

I'd say this is more of a side effect of the ability to do multiple variable assignment than a way to purposefully initialize an array.

In Ruby, you can assign multiple values at once using an array, you can return multiple values from a method. This gets returned as an array as well. Furthermore, since every expression in Ruby has a return value, x = 1, y = 2 returns the values for both of the assignment operations in an array as well.

ruby-1.9.2-p136 :001 > a, b = 3, 4
 => [3, 4] 
ruby-1.9.2-p136 :002 > a
 => 3 
ruby-1.9.2-p136 :003 > b
 => 4 
ruby-1.9.2-p136 :004 > def my_method
ruby-1.9.2-p136 :005?>   return "value1", "value2"
ruby-1.9.2-p136 :006?>   end
 => nil 
ruby-1.9.2-p136 :007 > my_method
 => ["value1", "value2"] 
ruby-1.9.2-p136 :008 > x = my_method
 => ["value1", "value2"] 
ruby-1.9.2-p136 :009 > x, y = my_method
 => ["value1", "value2"] 
ruby-1.9.2-p136 :010 > x
 => "value1" 
ruby-1.9.2-p136 :011 > y
 => "value2"

Upvotes: 4

Related Questions