Reputation: 2328
How can I shorten this expression?
if artist != 'Beck' && artist != 'Led Zeppelin'
5.times { puts 'sorry' }
end
Is there a shorthand check for two logical conditionals against one variable?
As an aside, this turned into
class String
def is_not?(*arr)
!arr.include?(self)
end
end
In our project.
Now we can do 'foo'.is_not?('bar', 'batz')
Upvotes: 0
Views: 55
Reputation: 168101
case artist
when 'Beck', 'Led Zeppelin'
else
5.times { puts 'sorry' }
end
Upvotes: 0
Reputation: 19855
Your specific case is pretty minimal, but if you have lots of unrelated conditions to test for lots of values you can set the tests up as lambdas in an array and use all?
. For instance, the following example filters all the integers between 1 and 100 for those which are > 20, < 50, even, and divisible by 3:
tests = [
->(x) { x > 20 },
->(x) { x < 50 },
->(x) { x.even? },
->(x) { x % 3 == 0 }
]
(1..100).each do |i|
puts i if tests.all? { |test| test[i] }
end
Upvotes: 1
Reputation: 230346
unless ['Beck', 'Led Zeppelin'].include?(artist)
5.times { puts 'sorry' }
end
Isn't any "shorter", but no obscure syntax trickery too. Just using regular array api. As a consequence, you can provide that array in any way you want. Load it from a file, for example. With any number of elements.
Upvotes: 3