Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby class inheritance issue

Tags:

ruby

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?

like image 690
ChrisCPO Avatar asked Mar 22 '26 01:03

ChrisCPO


1 Answers

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.

like image 71
Jordan Running Avatar answered Mar 25 '26 00:03

Jordan Running



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!