2

我想要一个像这样的代码:

x = Date

case x
when Date
  puts "Date"
when String
  puts "String"
else
  puts "Unknown"
end

我知道那x == Date是真的,但那x === Date是假的。所以当我期待“日期”时,我得到“未知”。

有什么方法可以更改上面块使用的运算符/函数,以便我可以获得预期的结果?

4

3 回答 3

5
x = Date

case x.name
when "Date"
  puts "Date"
when "String"
  puts "String"
else
  puts "Unknown"
end
于 2013-04-28T10:32:14.497 回答
2

AFAIK,如果您必须在 case 语句中进行比较,则必须===使用更详细的语法case

x = Date

case
when x == Date
  puts "Date"
when x == String
  puts "String"
else
  puts "Unknown"
end
于 2013-04-28T10:15:10.193 回答
2

另一种方法是:

class ComparableClass
  attr_accessor :klass

  def initialize(klass)
    @klass = klass
  end
end

class Class
  alias_method :'old_triple_equals', :'==='

  def ===(other)
    if other.is_a? ComparableClass
      self == other.klass
    else
      old_triple_equals(other)
    end
  end
end

klass = Date

case ComparableClass.new(klass)
when Date
  puts 'Its a date'
when String
  puts 'Its a string'
else
  puts 'Its something else'
end

#=> Its a date
于 2013-04-28T12:11:25.367 回答