Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is type conversion possible with inheritance in Ruby?

Tags:

oop

ruby

I'm using Ruby, and writing classes with inheritance.

For example:

class Canine
  def initialize
  end

  def make_noise
    puts "whoosh whoosh"
  end
end

class Dog < Canine
  def initialize
  end

  def make_noise
    puts "wong wong"
    super
  end
end

Now I have a dog object:

jack = Dog.new

Is it possible to call the make_noise() method of Canine through the dog object?

In other languages it would be a typecast, something like:

(Canine)jack.make_noise

Note this is not Ruby syntax, hence, my question.

Is it possible to do this in Ruby? And if so, how?

like image 388
Zack Xu Avatar asked Jun 24 '26 13:06

Zack Xu


1 Answers

You can do something like this:

Canine.instance_method(:make_noise).bind(jack).call

A better plan would be to just give the method in the super class an alias, or rename it.

like image 164
David Grayson Avatar answered Jun 26 '26 03:06

David Grayson



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!