ChrisCPO
ChrisCPO

Reputation: 463

Ruby class inheritance issue

I tried to get this result:

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

I did this:

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

What am I missing about Ruby's class system in order to implement this?

Upvotes: 3

Views: 44

Answers (1)

Jordan Running
Jordan Running

Reputation: 106117

Your intuition is good. At face value, the challenge seems incorrect, and if it's intended to be "a relatively simple code challenge," then I think that must be the case.

If the challenge is meant to be tricky, on the other hand, the specified result is certainly something that's possible in 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"

Try it on repl.it: https://repl.it/@jrunning/VisibleMustyHapuka

However, knowing nothing more about the challenge or its source, it's impossible to say whether or not this is the intended solution.

Upvotes: 4

Related Questions