我正在做一些case.. when..
,我发现了这种行为。
case vehicle.class
when Bike
puts "This is a Bike"
when Car
puts "This is a car"
else
puts "May be it's an UFO."
raise "ALIENS"
end
我发现,即使变量vehicle
是Bike
的一个实例,它也没有通过产生输出“这是一辆自行车”。相反,它引发了一个例外。
我觉得这很奇怪,因为以下代码会输出It's a string
。
case "FooBar"
when String
puts "It's a string"
else
puts "It's not a string"
end
我尝试了better_errors
的实时shell,发现了以下内容。
>> vehicle.class
=> Vehicle(id:integer, name: string, … , updated_at: datetime)
>> Vehicle
=> Vehicle(id:integer, name: string, … , updated_at: date time)
>> vehicle.class == Vehicle
=> true
>> vehicle.class === Vehicle
=> false
或者这与RACK_ENV
?
答案 0 :(得分:3)
如果vehicle
是Bike
的实例,则Bike === vehicle
为true
。另一方面,vehicle.class
为Bike
,因此Bike === vehicle.class
与Bike === Bike
相同,因为false
的类Bike
是Class
,不是Bike
。
取消class
。
case vehicle
when Bike
puts "This is a Bike"
when Car
puts "This is a car"
else
puts "May be it's an UFO."
raise "ALIENS"
end
答案 1 :(得分:1)
===
在后台的case
语句中使用,并测试右侧是否是左侧类的成员。 (请注意,结果不是可交换的。)
>> Fixnum === 2
=> true
>> class Vehicle; end
=> nil
>> class Truck < Vehicle; end
=> nil
>> Truck === Truck.new
=> true
>> Vehicle === Truck.new
=> true
>> Truck.new === Truck
=> false