0
  1. I want to know how I can declare multiple variables. I typed a,b=1 expecting to get a=1,b=1, but I got:

    a,b=1
    a #=> 1
    b #=> nil
    

    How am I able to do this?

  2. After this code, I did:

    a="Hello "
    b=a
    c="World~"
    b << c
    b #=> "Hello World"
    

    Why is b the same as a's value?

2
  • 4
    You can only ask one question at a time. That's a firm rule. However, if you post Q2 as a separate question, someone will probably point out that b=a causes a and b to point to the same object (e.g., a.object_id #=> 70270098990060; b.object_id; #=> 70270098990060) so if the object is changed it will be reflected in the values of both a and b. Commented Jan 25, 2015 at 7:23
  • 1
    As well as a=b=1, there's also "parallel assignment": a,b,c=1,2,3; [a,b,c]=>[1,2,3]. Commented Jan 25, 2015 at 7:27

3 Answers 3

6

To declare multiple vars on the same line, you can do that:

a = b = "foo"
puts a # return "foo"
puts b # return "foo" too

About your second question, when doing b << c, you are assigning c's value to b. Then, you are overriding previous value stored in b. Meanwhile, a keeps the same value because Ruby does not user pointers.

Sign up to request clarification or add additional context in comments.

Comments

2

What you are doing is called destructuring assignment. Basically, you take what is on the right side of the equals sign, and destructure it, or break it apart, and then assign each section to each corresponding variable on the left.

Ruby is super friendly, and is providing some syntactic sugar that might be confusing.

When you type this:

a, b = 1

You are really saying something closer to this:

[a, b] = [1, nil]

A good example of destructuring assignment can be found here. It's for JavaScript, but I like it because the syntax is very explicit about what is happen when you do such an assigment.

Comments

0

I suppose, in the case of

a, b, c = 1, 2

the runtime system works the following way:

a, b, c = [1, 2]

_result = ( a, b, c = (_values = [1, 2]) )

a = _values[0] # => 1

b = _values[1] # => 2

c = _values[2] # => nil

_result = _values # => [1, 2]

However, in the case of a single value on the right hand side: a, b = 1, the computation process looks a bit different:

_result = ( a, b = ( _value = (_values = [1]).first ) )

a = _values[0] # => 1

b = _values[1] # => nil

_result = _value # => 1

Can someone approve or disprove my assumption?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.