Forum: Ruby Derived-class initialization

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.
112b68b29c51d07c738d8f58e38f4d2d?d=identicon&s=25 Bryan Richardson (btrichardson)
on 2009-03-18 15:27
Hello all,

I'm having some trouble with extending an existing Ruby class in order
to add functionality.  Here's some example code:

class Graph
  ....
  ....
  def subgraph(*args)
    graph = self.new
    ....
    ....
    return graph
  end
end

class AwesomeGraph < Graph
  ....
  ....
  def do_something
    ....
    ....
  end
end

g = AwesomeGraph.new
a = g.subgraph(g.nodes)
a.do_something // ERROR! No Graph#do_something exists!

I was hoping 'self.new' would take into account the derived class used
upon creation, but it doesn't.

Any suggestions?

--
Thanks!
Bryan
53581739a445ad78250a676dabddf55f?d=identicon&s=25 James Coglan (Guest)
on 2009-03-18 15:36
(Received via mailing list)
2009/3/18 Bryan Richardson <btrichardson@gmail.com>

>    ....
>    ....
>    return graph
>  end
> end



This looks suspect, 'self' in this method looks like it will refer to
the
Graph instance, not the Graph class. Try self.class.new instead.
112b68b29c51d07c738d8f58e38f4d2d?d=identicon&s=25 Bryan Richardson (btrichardson)
on 2009-03-18 15:50
Yep... that worked. :)

--
Thanks!
Bryan

James Coglan wrote:
> 2009/3/18 Bryan Richardson <btrichardson@gmail.com>
>
>>    ....
>>    ....
>>    return graph
>>  end
>> end
>
>
>
> This looks suspect, 'self' in this method looks like it will refer to
> the
> Graph instance, not the Graph class. Try self.class.new instead.
This topic is locked and can not be replied to.