Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining logical operators in Ruby

I am currently working through Ruby Koans and I am faced with a situation where I want to accomplish the following:

if ones > 2 || twos > 2 || threes > 2 || fours > 2 || fives > 2 || sixes > 2
    #do something
end

Is there a better way to code this if-statement?

Any help is much appreciated.

like image 380
Aventuris Avatar asked Mar 25 '26 11:03

Aventuris


2 Answers

Do as below using Enumerable#any?:

if [ones,twos,threes,fours,fives,sixes].any?{|e| e > 2 }
   # do something
end

or as Jörg W Mittag suggested -

if [ones,twos,threes,fours,fives,sixes].any?(&2.method(:<))
   # do something
end
like image 141
Arup Rakshit Avatar answered Mar 27 '26 08:03

Arup Rakshit


Using Enumerable#max:

ones, twos, threes, fours, fives, sixes = 1, 2, 3, 4, 5, 6
[ones, twos, threes, fours, fives, sixes].max > 2
# => true
[ones, twos, threes, fours, fives, sixes].max > 6
# => false

If the condition is more complex using Enumerable#any? is more preferable as Arup Rakshit's answer.

like image 41
falsetru Avatar answered Mar 27 '26 07:03

falsetru



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!