【发布时间】:2013-12-28 04:54:58
【问题描述】:
TypeOfClass === TypeOfClass 是 false 的事实让我觉得违反直觉。在下面的代码中,即使field.class 是同一个类,它也会计算为false:
case field.class
when Fixnum, Float
field + other_field
when Date, DateTime, Time
field
else
puts 'WAT?'
end
我这样做了:
Fixnum === Fixnum # => false
Class === Class # => true
我找到another thread:
Integer === 3 # => true
Fixnum === 3 # => true
3.class # => Fixnum
我找不到这种语言设计的原因。语言设计者在融入这种行为时是怎么想的?
我认为这与another thread 中提供的答案有关。假设Numeric === Integer 并非不自然,因为Integer 是Numeric 的更具体类型。但是,它不是:
Numeric === Integer #=> false
我认为case 声明或=== 需要谨慎。如果这个操作符是we think it is,那么Numeric应该是Numeric,Integer应该是Numeric等等。
有没有人解释一下为什么这个特性没有扩展到类?如果比较类是该类祖先的成员,则返回 true 似乎很容易。
根据下面提交的答案,代码最初是对Time 进行分类(由ActiveSupport:CoreExtensions::Integer::Time 和ActiveSupport:CoreExtensions::Float::Time 扩展):
Timeframe = Struct.new(:from, :to) do
def end_date
case self.to
when Fixnum, Float
self.from + self.to
when Date, DateTime, Time
self.to
else
raise('InvalidType')
end
end
end
在控制台中,我得到:
tf = Timeframe.new(Time.now, 5.months)
# => #<struct Timeframe from=Tue Dec 10 11:34:34 -0500 2013, to=5 months>
tf.end_date
# => RuntimeError: InvalidType
# from timeframe.rb:89:in `end_date'
【问题讨论】:
-
再一次,我看不出不将
self.to.class更改为self.to的原因。 -
在发布问题之前,我尝试消除了
.class电话,但仍然没有骰子... -
好的,为什么它不起作用?尝试在case语句之前打印
self.to的类,看看你没有得到任何其他你不期望的类,也许是String? -
我在发布问题之前尝试过...
pry(main)> tf.end_date12960000RuntimeError: InvalidType呃。对不起。
标签: ruby class types switch-statement comparison-operators