On 12 Nov 2006, at 17:37, dblack / wobblini.net wrote: > Hi -- > > On Mon, 13 Nov 2006, Sebastian Reid wrote: > >> Hi all. >> >> I've been working on some Ruby projects using the Rails framework >> and getting on well, however recently I've started on some >> projects using Ruby alone and have run into some issues as the >> task gets a little more complicated. >> >> One particular script is giving me trouble and I suspect it is >> due to my Perly ways. Below is a pastebin of the code. As some >> I'm sure can tell, it is an rbot plugin that right now doesn't do >> a whole lot. >> >> http://pastebin.com/822611 >> >> The highlighted line is flagging up the error: >> >> TypeError: no implicit conversion from nil to integer >> >> on line 18 (highlighted). >> >> Now this is looking to me like a variable instantiation issue >> which brings us back to Perl. In Perl that line would be >> perfectly legal (though some would debate its elegance) and hashes >> and arrays would be created as and when required. > > In Ruby that won't work (as you've seen), specifically because [] is a > method. When you do: > > x["y"] > > you're really doing: > > x.[]("y") > > Arrays and hashes have a [] method, but so can any object; so the > presence of [] doesn't narrow down the field. > >> I'm willing to accept that this may not be the best way to do >> things in Ruby, thus I come to you to ask for a quick rundown on >> best practices in these situations. >> >> I've played around with default procs and the like in the >> initialisation routine to no avail. There is an implicit dump >> somewhere which causes problems. What would be the best way to >> deal with this type of thing? > > You'd probably be likely to see @registry initialized in the > initialize method, and then its elements initialized conditionally > along the way: > > (@registry["content"] ||= []).push(m.message) > > You can certainly economize on this if you do: > > @registry = Hash.new {|h,k| h[k] = [] } > > though this approach might be less slick as you get into deeper > nesting. > > You might want to encapsulate the behavior in a class or module, and > even perhaps have a class representing @registry["context"]. > > > David I think we actually tried @registry = Hash.new {|h,k| h[k] = [] } which was where the problem with the dump came in. Desperately trying not to turn this into a set of classes since it should be fairly simple otherwise, but I can see it drifting that way. > >