Subclassing weirdness in rb-gsl

N

none

Does anyone know why it would be impossible for me to subclass
GSL::Matrix? This might be evidence of my lack of sophistication in
Ruby or OO, but perhaps there is an easy or interesting answer. Here
is the code:

class SuperMatrix < GSL::Matrix
def initialize
@foo = 2
super
end
def whatever
return @foo
end
end

m = SuperMatrix.new([1,2,3], [4,5,6])
irb(main):058:0> m.inspect
GSL::Matrix
[ 1.000e+00 2.000e+00 3.000e+00
4.000e+00 5.000e+00 6.000e+00 ]

irb(main):056:0> m.whatever
NoMethodError: undefined method `whatever' for
#<GSL::Matrix:0xb6f75264>
from (irb):56

Thanks to all for a great language and community!
 
N

nobuyoshi nakada

Hi,

At Thu, 7 Jul 2005 15:10:47 +0900,
none wrote in [ruby-talk:147381]:
Does anyone know why it would be impossible for me to subclass
GSL::Matrix? This might be evidence of my lack of sophistication in
Ruby or OO, but perhaps there is an easy or interesting answer. Here
is the code:

Because rb-gsl doesn't follow allocation framework, but
defines singleton method "new" in older fashon.
 
S

Steven Jenkins

none said:
Does anyone know why it would be impossible for me to subclass
GSL::Matrix? This might be evidence of my lack of sophistication in
Ruby or OO, but perhaps there is an easy or interesting answer. Here
is the code:

class SuperMatrix < GSL::Matrix
def initialize
@foo = 2
super
end
def whatever
return @foo
end
end

You know why now, but this might help:

require 'delegate'
require 'gsl'

class SuperMatrix < DelegateClass(GSL::Matrix)
def initialize(*m)
@foo = 2
sm = GSL::Matrix.new(*m)
super(sm)
end
def whatever
return @foo
end
end

$ irb -r t
irb(main):001:0> m = SuperMatrix.new([1,2,3], [4,5,6])
[ 1.000e+00 2.000e+00 3.000e+00
4.000e+00 5.000e+00 6.000e+00 ]
=> #<GSL::Matrix:0xb796bc14>
irb(main):002:0> m.whatever
=> 2

The fact that 'inspect' is delegated has a somewhat surprising result,
but it appears to do what you want. 'Forwardable' is also related.

Steve
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top