Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you check if multiple values are the same on the same line in ruby on rails?

Basically, I am trying to check if 6 of my values are the same. I tried stringing them:

if val1 == val2 == val3 == val4 == val5 == val6
  #...
end

But this errors out. Is this possible using another method? Thanks

like image 361
perseverance Avatar asked Nov 13 '12 23:11

perseverance


3 Answers

Try this:

if [val1, val2, val3, val4, val5, val6].uniq.count == 1
  #...
end

If you wanna get fancy, you can try this

unless [val2, val3, val4, val5, val6].find{ |x| x != val1 }
  # ...
end

The above will stop as soon as it finds an element that is not equal to val1, otherwise, the block will be executed.

like image 119
Kyle Avatar answered Nov 09 '22 09:11

Kyle


A cute way:

[val1,val2,val3,valN].uniq.size == 1

A more prosaic way:

[val2,val3,valN].all?{ |x| x == val1 }
like image 39
dbenhur Avatar answered Nov 09 '22 09:11

dbenhur


If values are by any chance Fixnum, this sexy line would work:

if val1 == val2 & val3 & val4 & val5 & val6
  # ...
end

if not, then this fatty would work for any type

if [val1] == [val2] & [val3] & [val4] & [val5] & [val6]
   # ...
end
like image 39
Dejan Simic Avatar answered Nov 09 '22 09:11

Dejan Simic