Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby number equal?

Tags:

ruby

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?

like image 558
x_z Avatar asked Dec 08 '22 14:12

x_z


2 Answers

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.

like image 150
ForeverZer0 Avatar answered Dec 21 '22 12:12

ForeverZer0


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

like image 25
Simple Lime Avatar answered Dec 21 '22 12:12

Simple Lime