Ruby's case statement uses ===
by default. Is there a way to make it use 'equals to' (i.e. ==
) instead?
The motivation for doing so is because I have 5 if
statements that would very nicely be replaced by a switch, but I was a little surprised to learn that
datatype = "string".class
if datatype == String
puts "This will print"
end
is not the same as
case datatype
when String
puts "This will NOT print"
end
You cannot let case
to not use ===
, but you can redefine ===
to use ==
.
class Class
alias === ==
end
case datatype
when String
puts "This will print"
end
# >> This will print
Alternatively, you can create a specific class for doing that.
class MetaClass
def initialize klass
@klass = klass
end
def ===instance
instance == @klass
end
end
def meta klass
MetaClass.new(klass)
end
case datatype
when meta(String)
puts "This will print"
end
# >> This will print
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