Dear Ruby Experts,
I’m somewhat new to Ruby and have got a problem which seems quite strange
to me. I intend to use a class as container for an array of instances of
an other class.
class A
def funA ()
puts "I’m alive!"
end
end
class B
def initialize ()
@aList = Array.new
end
def funB ()
# this code follows below
end
end
One time, my program creates an instance of B and calls funB:
b = B.new
b.funB
funB fills the list ‘aList’ with some instances of A:
def funB ()
# append a new element to the list
if @aList.empty?
# in fact, i check if array size is big enough and
# do the append if it doesn’t
@aList = @aList + Array.new(1, A)
end
# now we should have at least one instance of A in @aList, eh?
# let’s call the instance method
@aList[0].funA # this is line 20!
end
end
And I expected this to work properly and waited for the “I’m alive”. But
it doesn’t. I get this error:
test.rb:20:in funB': undefined method
funA’ for A:Class (NameError)
from /home/pooh/bin/test.rb:33
and don’t know what it is intended to tell me.
I tried to find out more about @aList and its type and replaced line 20
with several checks:
puts @aList.type » Array
I understand, so far.
puts (@aList).type » A
This is confusing. Why the difference? Did I miss some special meaning of
"()"?
puts "#{(@aList).type}" » Array
Should produce the same as above, but produces what I expected first. Hum?
But things are getting even more strange:
puts @aList.at(0).type » Class
puts @aList[0].type » Class
Wtf…? The Ruby book says “arr.at( anInteger ) -> anObject or nil” so I
expected to get “A” as type and not “Class”.
You might understand, I’m somewhat confused. The last statement at least
showed me the meaning of the top error message, because obviously
@aList[0] returns a “Class” not an object instance.
But what shall I do to get my method called?
Yours,
Rene
···
–
Dipl.-Inform. René Tschirley http://www.cs.tu-berlin.de/~pooh
TU Berlin, Computer Graphics and Computer Assisted Medicine research group