Two number compare, like below:
#!/usr/bin/ruby
a=1000, b=1000, c=1000, d=1000
puts a==b, c==d
but print:
false
true
Why Ruby compare result like this?
Ruby's shortcut for setting multiple variables on one line is a little different than C-esque languages.
As pointed out in SimpleLime's Answer, the syntax you are using actually creates an array of the a
variable.
As another pointed out in comment, the way your example is written would evaluate to the following:
a = [1000, (b = 1000), (c = 1000), (d = 1000)]
While b
, c
, and d
set as expected, a
does not. a
is set to an array, while b
, c
, and d
are set to 1000
, since variable = value
is actually a method call that returns the given value.
The Ruby syntax for what you really intended would look like this:
a, b, c, d = 1000, 1000, 1000, 1000
or what it actually evaluates to:
a, b, c, d = [1000, 1000, 1000, 1000]
You can also still do the other shortcut syntax that is pretty common if all the values are the same.
a = b = c = d = 1000
But beware of this syntax if not using "value" types, such as numerics or booleans, as all the objects will share the same reference.
In ruby you don't need the square brackets []
to create an array. So your variable creation line isn't doing what you think:
a=1000, b=1000, c=1000, d=1000
p a # [1000, 1000, 1000, 1000]
p b # 1000
p c # 1000
p d # 1000
So then, a == b
is comparing the array [1000, 1000, 1000, 1000] == 1000
, which is obviously false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With