Derived-class initialization

B

Bryan Richardson

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?
 
J

James Coglan

[Note: parts of this message were removed to make it a legal post.]

2009/3/18 Bryan Richardson said:
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



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.
 
B

Bryan Richardson

Yep... that worked. :)

--
Thanks!
Bryan

James said:
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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,176
Messages
2,570,947
Members
47,498
Latest member
log5Sshell/alfa5

Latest Threads

Top