Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single line multiple assignment in ruby

Tags:

ruby

Is it good to assign an empty array in one line ?

arun@arun:~$ irb
   irb(main):001:0> a = b = c = []
=> []
irb(main):002:0> b << "one"
=> ["one"]
irb(main):003:0> p a
["one"]
=> nil

Since i expect 'a' to be [] but it show the value of b means "one". Is this expect one ?

I also try with string and integer object.

irb(main):004:0> d = e = f = 0
=> 0
irb(main):005:0> f = 6
=> 6
irb(main):006:0> p d
0
=> nil
irb(main):007:0>

irb(main):007:0> q = w = e = r = "jak"
=> "jak"
irb(main):008:0> e = "kaj"
=> "kaj"
irb(main):009:0> p w
"jak"
=> nil
irb(main):010:0> p e
"kaj"
=> nil
irb(main):011:0>

It is working as i expected. Then why not array ?

like image 885
Jak Avatar asked Jul 26 '11 09:07

Jak


People also ask

How do I assign multiple variables to one line?

When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should be to the right of the assignment operator.

How do you assign the same value to multiple variables in Ruby?

In Ruby, multiple assignments can be done in a single operation. Multiple assignments contain an expression that has more than one lvalue, more than one rvalue, or both. The order of the values assigned to the right side of = operator must be the same as the variables on the left side.

How do you return multiple values in Ruby?

You can return multiple values on a method using comma-separated values when you return the data. Here we are creating a method called multiple_values that return 4 values. Each of them separated by a comma, in this form when we call multiple_values as a result, we will see an array with all these values.

Which symbol is used to assign multiple values to multiple variables A B C D?

You can assign multiple values to multiple variables by separating variables and values with commas , . You can assign to more than three variables.


1 Answers

What you are doing is assingning [] to c, which you then assign to b, which finally gets assigned to a.

>> a = b = c = []
>> a.object_id
=> 2152679240
>> b.object_id
=> 2152679240
>> c.object_id
=> 2152679240

What you want is

>> a,b,c = [], [], []
=> [[], [], []]
>> a.object_id
=> 2152762780
>> b.object_id
=> 2152762760
>> c.object_id
=> 2152762740

Edit: the examples work because you just go and plain assign a new value (Fixnums can't be mutated anyway). Try modifying the string in-place instead:

>> q = w = e = r = "jak"
=> "jak"
>> e << 'i'
=> "jaki"
>> w
=> "jaki"
like image 167
Michael Kohl Avatar answered Oct 21 '22 04:10

Michael Kohl