Ruby doesn't have any sort of fall-through for case
.
One alternative be a series of if
statements using the ===
method, which is what case
uses internally to compare the items.
has_matched? = false
if '2' === var
has_matched? = true
# stuff
end
if '3' === var
has_matched? = true
# other stuff
end
if something_else === var
has_matched? = true
# presumably some even more exciting stuff
end
if !has_matched?
# more stuff
end
This has two glaring issues.
It isn't very DRY: has_matched? = true
is littered all over the place.
You always need to remember to place var
on the right-hand-side of ===
, because that's what case
does 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 an else_do
method 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:
class String
def ===(other_str)
self.strip[0, other_str.length].downcase == other_str.downcase
end
end
class Array
def ===(str)
self.any? {|elem| elem.include?(str)}
end
end
class Fixnum
def ===(str)
self == str.to_i
end
end
Essentially, when Ruby encounters case var
, it will call ===
on the objects against which you are comparing var
.