calling child methods in parent

Discussion in 'Ruby' started by Dave Ru, Feb 8, 2006.

  1. Dave Ru

    Dave Ru Guest

    ------=_Part_7982_13889138.1139360052255
    Content-Type: text/plain; charset=ISO-8859-1
    Content-Transfer-Encoding: quoted-printable
    Content-Disposition: inline

    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 =3D 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.

    ------=_Part_7982_13889138.1139360052255--
     
    Dave Ru, Feb 8, 2006
    #1
    1. Advertising

  2. > 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.
     
    Matthew Smillie, Feb 8, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?Utf-8?B?Smlt?=

    Calling parent methods from a child

    =?Utf-8?B?Smlt?=, Jan 12, 2005, in forum: ASP .Net
    Replies:
    5
    Views:
    5,690
    Karl Seguin
    Jan 13, 2005
  2. davout
    Replies:
    0
    Views:
    554
    davout
    Apr 18, 2004
  3. Jeff Rodriguez
    Replies:
    23
    Views:
    1,141
    David Schwartz
    Dec 9, 2003
  4. Noel Dolan
    Replies:
    0
    Views:
    242
    Noel Dolan
    Jul 18, 2004
  5. Bitswapper
    Replies:
    5
    Views:
    154
    Prasad, Ramit
    Aug 27, 2013
Loading...

Share This Page