Reputation: 2286
Is there a more concise way of structuring the following if
statement?
if self.itemsize.downcase.include? "a3" or
self.itemsize.downcase.include? "a4" or
self.itemsize.downcase.include? "a5" or
self.itemsize.downcase.include? "dl"
puts "yadda yadda"
end
Perhaps with an array? eg if self.itemsize.downcase.include? ["a3", "a4", "a5", "dl"]
Upvotes: 1
Views: 117
Reputation: 12252
How I'd probably do it:
p "yadda yadda" if ["a3", "a4", "a5", "dl"].include?(self.itemsize.downcase)
I would move the array to a class/module variable so that it's not instantiated every time.
EDIT:
What OP actually wants is to test if any of the strings "a3", "a4", "a5", "dl"
is a sub-string of self.itemsize.downcase
. The above tests if self.itemsize.downcase is equal to any of the strings, which is different from the former. Thanks clyfe for pointing that out.
Upvotes: 3
Reputation: 27875
Solution with a regular expression:
if self.itemsize =~ /(a3|a4|a5|dl)/i
#if self.itemsize =~ /\A(a3|a4|a5|dl)\Z/i
puts "yadda yadda"
end
Upvotes: 3
Reputation: 23770
size = itemsize.downcase # memoize
if %w(a3 a4 a5 dl).any? {|e| size.include? e}
puts "yadda yadda"
end
Upvotes: 8