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.
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
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.
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