-1

我正在做一些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

我在 live shell 中进行了尝试,better_errors发现了以下内容。

>> 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吗?

4

2 回答 2

3

如果vehicle是 的一个实例Bike,那么Bike === vehicletrue。另一方面,vehicle.classis Bike,因此Bike === vehicle.class与 相同Bike === Bike,这是因为isfalse的类,而不是。BikeClassBike

起飞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
于 2013-06-15T14:00:42.623 回答
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
于 2013-06-15T14:08:11.710 回答