Douglas A. Seifert
8/23/2006 4:39:00 PM
Nathan Smith wrote:
> On Thu, 24 Aug 2006, William Crawford wrote:
>
>
>> Julian 'Julik' Tarkhanov wrote:
>>
>>> On 23-aug-2006, at 17:39, James Edward Gray II wrote:
>>>
>>>
>>>> Try the correction above. ;)
>>>>
>>> Actually I am curious to know:
>>>
>>> class Parent
>>> def something
>>> end
>>>
>>> def another
>>> # do foo
>>> end
>>> end
>>>
>>> class Child < Parent
>>> def something
>>>
>> super # call _another_ instance method BUT of the
>>
>>> superclass, not one's own
>>> end
>>>
>>> def another
>>> # do bar instead of foo
>>> end
>>> end
>>>
>>> is that at all possible somehow? Just out of curiosity.
>>>
>> I think that's what you are wanting. It calls the parent's 'another'
>> method with the exact same parameters as were passed to child's
>> 'another' method. If you want parameters that are different, simply
>> specify them as if you were calling 'Parent.another(parameter)'. (ie:
>> super(parameter) )
>>
>
> I think he's wanting to know if it's possible to call a different method
> of the superclass than the method that the interpreter is in. For example,
>
> class A
> def zoo
> puts "in zoo"
> end
> end
>
> class B < A
> def hoo
> super.zoo
> end
> end
>
> b = B.new
> b.hoo
>
>
> will not work -- you must explicitly define method #zoo in class B in
> order to call the super version of it in class A. Is there a way to make
> the above code work, short of defining zoo in B? I'm curious about this
> also.
>
> Nate
>
Why would you need to explicitly reference super? It is not necessary:
$ irb
irb(main):001:0> class Parent
irb(main):002:1> def zoo
irb(main):003:2> puts "zoo in Parent!"
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0>
irb(main):007:0* class Child < Parent
irb(main):008:1> def hoo
irb(main):009:2> zoo
irb(main):010:2> end
irb(main):011:1> end
=> nil
irb(main):013:0> c = Child.new
=> #<Child:0x39dd78>
irb(main):014:0> c.hoo
zoo in Parent!
=> nil
irb(main):015:0>
If there is some common functionality that needs to be accessed by two
methods, one defined in the child class, the other defined in the parent
class, I'd say refactor it out into a method in the Parent class and
call it from wherever it is needed:
$ irb
irb(main):001:0> class Parent
irb(main):002:1> def common
irb(main):003:2> puts "common in Parent"
irb(main):004:2> end
irb(main):005:1> def foo
irb(main):006:2> puts "foo in Parent"
irb(main):007:2> common
irb(main):008:2> end
irb(main):009:1> end
=> nil
irb(main):010:0> class Child < Parent
irb(main):011:1> def bar
irb(main):012:2> puts "bar in Child"
irb(main):013:2> common
irb(main):014:2> end
irb(main):015:1> end
=> nil
irb(main):016:0> c = Child.new
=> #<Child:0x392c30>
irb(main):017:0> c.bar
bar in Child
common in Parent
=> nil
irb(main):018:0> c.foo
foo in Parent
common in Parent
=> nil
Cheers,
Doug