Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a ruby case statement use equals to (==) rather than threequals (===)

Tags:

ruby

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
like image 921
stevec Avatar asked Dec 24 '22 01:12

stevec


1 Answers

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
like image 52
sawa Avatar answered Feb 15 '23 23:02

sawa