I am using Ruby on Rails 3 and I would like to use a case statement that even after matching a when statement can continue to checks other when statement until the last else.
For example
case var
when '1'
if var2 == ...
...
else
...
puts "Don't make nothig but continue to check!"
# Here I would like to continue to check if a 'when' statement will match 'var' until the 'else' case
end
when '2'
...
...
else
put "Yeee!"
end
Is it possible in Ruby? If so, how?
Ruby doesn’t have any sort of fall-through for
case.One alternative be a series of
ifstatements using the===method, which is whatcaseuses internally to compare the items.This has two glaring issues.
It isn’t very DRY:
has_matched? = trueis littered all over the place.You always need to remember to place
varon the right-hand-side of===, because that’s whatcasedoes behind the scenes.You could create your own class with a
matches?method that encapsulates this functionality. It could have a constructor that takes the value you’ll be matching against (in this case,var), and it could have anelse_domethod that only executes its block if its internal@has_matched?instance variable is still false.Edit:
The
===method can mean anything you want it to mean. Generally, it’s a more “forgiving” way to test equivalency between two objects. Here’s an example from this this page:Essentially, when Ruby encounters
case var, it will call===on the objects against which you are comparingvar.