Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tricky ruby class init---- why same class initialize output differently?

Tags:

class

ruby

look this class:

class Test
  def initialize a, b, c
    @a = a, @b = b, @c = c
  end
  end

class AnotherTest
  def initialize a, b, c
    @a = a
    @b = b
    @c = c
  end
end

array = []

array.push Test.new "a1" ,"b1", "c1"
array.push AnotherTest.new "a2" ,"b2", "c2"

p array

I think this should be the same,but not:

<Test:0x000000022aba78 @b="b1", @c="c1", @a=["a1", "b1", "c1"]>
<AnotherTest:0x000000022ab9b0 @a="a2", @b="b2", @c="c2">]

Anybody who can give me an explain?

like image 212
LeoShi Avatar asked Aug 23 '26 23:08

LeoShi


1 Answers

If you try in irb this expression:

a = "something" #=> "something"

As you can see, the assignment operation returns the result, because in ruby every expression should return something. So then this expression:

@b = b #=> b

will return the value of @b. Then in this expression

@a = a, @b = b, @c = c

where @b = b and @c = c will evaluate to b and c

So finally we will have this expression:

@a = a, b, c

And as you know it's another form for initialization of array

@a = [a, b, c]

This code will work equivalently to yours:

class Test
  def initialize a, b, c
    @a = a, b, c
    @b = b
    @c = c
  end
end

Addition: The order of evaluating is significant. If you try this expression:

@a = a, (@b = b, @c = c)

Firstly, it will evaluate everything in parentheses:

@b = b, @c = c #=> @b = [b,c] and @c = c

So then we'll get this

@a = [a,[b,c]]
@b = [b,c]
@c = c
like image 199
megas Avatar answered Aug 26 '26 23:08

megas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!