From: "Florian Aßmann" Date: 2007-06-15T06:53:33+09:00 Subject: Re: severe newbie question (class, fixnum, array) Hi Colin, First of all: http://whytheluckystiff.net/ruby/pickaxe/ Am 14.06.2007 um 23:25 schrieb Colin Summers: > I worked a lot in tcl, and this is my first day of trying something in > Ruby. Second, maybe. > > class Thread > def initialize number > @number = number ; # > @replies = 0 ; > end ; # initialize > > def filename > dirname = "./data/" ; # the directory where the files are kept > filename = dirname + @number.toS + "-" + @replies.toS + ".html" > return filename > end ; # filename > > end ; # Thread definition > > puts "Finished definitions." > > thread[1727] = Thread.new 1727 > > puts "The filename would be: " > puts thread[1727].filename > > > Of course, that doesn't work. It is unhappy with the code to create > the filename, since .toS is not a method for fixnum (which apparently > is what @number is, but I never TOLD it that was a fixnum). See: http://whytheluckystiff.net/ruby/pickaxe/html/tut_stdtypes.html The method you probably search for is to_s... > > And I can't seem to define "thread" to be an array of class Thread > objects. I want to refer to thread[1702] and thread[291] and hop > around like that. class Thread already exists and is, as its name foreshadows, for http://whytheluckystiff.net/ruby/pickaxe/html/tut_threads.html > > (And, perhaps a more advanced question, right now I am making the > thread number part of the object, ultimately for a gorgeous bit of > code it seems like the object should just know the index of the array > instead, so if I ask thread[32] what it's filename is it would know > that it is thread #32. Can it do that?) class FileThread DIR = 'data'.freeze # defines class constant @@instances = Array.new # initializes class variable as array def self.new number # overwrites class method @@instances[number] ||= super # set array elem with result from parent class if not already set end def self.[] number # defines new class method new number # class class method new end def initialize number @number = number @replies = 0 end def filename # see http://whytheluckystiff.net/ruby/pickaxe/html/ref_c_file.html @filename ||= File.expand_path File.join( DIR, "#{ @number }-# { @replies }.html" ) end end FileThread[1].filename # => "#{ Dir.getwd }/data/1-0.html" Sincerely Florian