Robin Stocker
8/20/2006 12:29:00 PM
Dave Snowdon wrote:
> Hi folks
>
> I'm working on some code that extracts data from a set of XML files
> using REXML stores this as arrays of arrays of floats (one array of
> floats per file), does some processing and then writes the results to 4
> text files for visualisation with gnuplot.
>
> However, what happens is that although 4 files get created all the data
> gets saved in the first one to be opened. It's as if the block in
> writeMatrix() stores the reference to the first File object and uses
> that on the other 3 method invocations. If that's the case then I've
> obviously failed to understand the appropriate way to use a block.
>
> What would be a better way to code this in ruby?
Hi,
So I took your code, made it look more like Ruby code (snake_case),
simplified it, added example data and ran it. The resulting files were
all as I think they should be. The problem you are having has to lie
somewhere else in your code. Are you shure the class variables
*_DATA_FILE are right, or maybe they all contain the same file name?
Anyway, here's the code:
class TuneInputData
@@LUMINANCE_DATA_FILE = "luminance.data"
@@VOICE_DATA_FILE = "voice.data"
@@SOUND_DATA_FILE = "sound.data"
@@RHYTHM_DATA_FILE = "rhythm.data"
@@COLOURFULNESS_DATA_FILE = "colourfulness.data"
def initialize
@image_vector = [[1, 2, 3], [3, 2, 1]]
@voice_vector = [[4, 5, 6], [6, 5, 4]]
@sound_vector = [[7, 8, 9], [9, 8, 7]]
@rhythm_vector = [[10, 11, 12], [12, 11, 10]]
end
def write_data
write_matrix(@@LUMINANCE_DATA_FILE, @image_vector)
write_matrix(@@VOICE_DATA_FILE, @voice_vector)
write_matrix(@@SOUND_DATA_FILE, @sound_vector)
write_matrix(@@RHYTHM_DATA_FILE, @rhythm_vector)
# write_column(@@COLOURFULNESS_DATA_FILE, @image_colourfulness)
end
def write_matrix(filename, matrix)
File.open(filename, 'w') do |file|
file.puts matrix.collect{ |row| row.join(' ') }
end
end
end
t = TuneInputData.new
t.write_data
Hope it helped,
Robin