Ruby类继承问题

3
我尝试得到这个结果:
Car.class.name # => "Car"
Truck.class.name # => "Truck"
Van.class.name # => "Van" 
Car/Truck/Van.superclass.name # => "Vehicle" 

我做了这个:
require "rspec/autorun"

class Vehicle
end

class Car < Vehicle
end

class Van < Vehicle
end

class Truck < Vehicle
end

describe Car do
  describe ".class.name" do
    it "returns name of the class" do
      expect(Car.class.name).to eq "Car"
    end
  end
end

我在实现这个功能时忽略了关于Ruby类系统的什么内容?

你有编程挑战的链接吗? - Sagar Pandya
1个回答

4
你的直觉很好。表面上看,这个挑战似乎是不正确的,如果它旨在成为“相对简单的代码挑战”,那么我认为一定是这种情况。
另一方面,如果这个挑战意在棘手,那么指定的结果肯定是Ruby中可能实现的内容。
class Vehicle
  def self.class
    self
  end
end

class Car < Vehicle; end
class Van < Vehicle; end
class Truck < Vehicle; end

p Car.class.name # => "Car"
p Truck.class.name # => "Truck"
p Van.class.name # => "Van"
p Car.superclass.name # => "Vehicle"

在repl.it上尝试: https://repl.it/@jrunning/VisibleMustyHapuka

然而,如果不了解挑战的具体内容和来源,就无法确定这是否是预期的解决方案。


好的观察!您知道更改 self.class 是否会对类在其他上下文中的行为产生任何影响吗? - Silvio Mayolo
是的,我知道解决方案很简单,但我过于复杂化了,并且在理解“为什么”方面遇到了困难。 - ChrisCPO
@SilvioMayolo 我肯定会预期这会导致一些不寻常的行为,对于那些假设.class行为的代码来说,这是 Ruby 生态系统中的大量代码。 - Jordan Running

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接