Forum: Ruby calling child methods in parent

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bd731dfa6c47dbc31580be8f32aa4998?d=identicon&s=25 Dave Ru (Guest)
on 2006-02-08 01:56
(Received via mailing list)
Hi-
   This may be a pretty easy question but I'm new to ruby

Say I have a class like this

class MyClass

  def myCallingMethod
      myMethodToOverrider("hello")
  end

   def myMethodToOverride(string)

    end
end

and I want to create a chile method like so

class ChildClass < MyClass
    def myMethodToOverride(string)
         puts string
     end
end

Then I create an instance of my child class

child = ChildClass.new()

then I call myCallingMethod

child.myCallingMethod()

is there anyway to have the method in the parent object call the
overriden
method in the child?

Thanks in advance.
31af45939fec7e3c4ed8a798c0bd9b1a?d=identicon&s=25 Matthew Smillie (Guest)
on 2006-02-08 03:24
(Received via mailing list)
> is there anyway to have the method in the parent object call the
> overriden
> method in the child?

That's the default behaviour, actually.  In C++ terms, all methods
are virtual.

Observe:

  class Parent
    def say_what
      virtual_method("Hello World")
    end
    def virtual_method(str)
      "I say: #{str}"
    end
  end

  class Child < Parent
    def virtual_method(str)
      "My parent says: #{str}"
    end
  end

  william = Parent.new
  william.say_what
  # => "I say: Hello World"

  billy = Child.new
  billy.say_what
  # => "My parent says: Hello World"

matthew smillie.
This topic is locked and can not be replied to.