From: David Alan Black Date: 2002-01-31T10:55:23+09:00 Subject: Re: Newbie question about mixins Hello -- Welcome to Ruby :-) On Thu, 31 Jan 2002, Mark Wilson wrote: > I have a module that I want to use as a mixin. I have defined a method > within the module that attempts to assign a value to a hash 'slot': > > module myMod > def mixinMethod(param1, param2) > @hashVar[param1] = param2 > end > end My Ruby balks at being asked to call a module "myMod".... dblack@laptop:~$ ruby -ve 'module myMod; end' ruby 1.6.5 (2001-09-19) [i686-linux] -e:1: class/module name must be CONSTANT (You need a constant identifier, which begins with an uppercase letter.) > I include this module into my class, and call 'mixinMethod'. I get a > NameError because, apparently, I have not told the program that 'hashVar' is > a hash table. Where should I do a Hash.new() or other initialization? Here's one pretty common idiom for telling Ruby that you only want to assign something to a variable if that variable is uninitialized (well, technically, if that variable evaluates to "false" in a Boolean sense, which covers the case of uninitialized variables): h ||= Hash.new which is shorthand for: h = h || Hash.new Once h is initialized, this essentially functions as "h = h". David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav