From: Tim Hunter Date: 2008-06-12T07:38:59+09:00 Subject: Re: Class (not instance) Initializer Greg Willits wrote: > I would like to populate a class variable using a method > > class SomeThing > @@some_data > populate_some_data > > def populate_some_data > end > end > > > I expected that prefixing the method with self would work. It doesn't. > > ... > self.populate_some_data > > def self.populate_some_data > end > ... > > Poking around in a couple books I don't see anything that addresses > this. What's the correct syntax for this? Or, if there is no way to run > a method, what's the best way to pull a trigger to have @@some_data > populated the first time any object of SomeThings is instantiated? > > -- gw Well, if you want to wait to do the initialization until the first object is created, then something like this might work: def initialize populate_some_data if @@some_data == nil ... end But if all you want to do it initialize @@some_data, just put the initialization code in the class definition: class SomeThing @@some_data = [1,2,3] def initialize ... end end Ruby will execute the code as it creates the class. Try this: ~$ irb irb(main):001:0> class SomeThing irb(main):002:1> puts "Hiya!" irb(main):003:1> end Hiya! => nil -- RMagick: http://rmagick.rubyforge.org/ RMagick 2: http://rmagick.rubyforge.org/rmagick2.html