Matt C
6/30/2005 1:04:00 AM
New to Ruby. Probably my terminology will be a bit off.
In the Pickaxe book (first edition) they show a clever little trick with
the SongList class, where you can use [] to pull a song from the list using
either the integer index or the name of the song.
I wanted to try something like that, but with a subclass of Array rather
than writing a wrapper around an array. I had the idea I might be able to
use super:
class TalkerArray < Array #will hold a collection of Talkers.
def [](key)
if key.kind_of?(Integer)
return super[key]
else
return self.find{|t| t.name = key} #talkers have .name property.
end
end
end
but it didn't work (*). I bet there is a simple way to make something like
this work while inheriting from Array, though. Can anyone show me?
Thanks,
Matt
*: The error message I got was strange:
E:/matt/ruby/usr/ww/chat.rb:173:in `[]': undefined method `[]' for #
<Talker:0x2a5be68 @name="bob", @last_msg=0> (NoMethodError)
Why the heck is it looking at the Talker object? I must not understand
what 'super' does. Anyway, I put this as a postscript because it's kind of
a side issue for me. I'm guessing I don't really need 'super', or
understanding 'super', to override [] the way I want to. So I can worry
about that some other day. Which is not to say I won't listen if someone
wants to explain, it's just not my priority of the moment. Ok, really
done typing now.