I’m just starting out using Ruby and I’ve written a bit of code to do basic parsing of a CSV file (Line is a basic class, omitted for brevity):
class File def each_csv each do |line| yield line.split(',') end end end lines = Array.new File.open('some.csv') do |file| file.each_csv do |csv| lines << Line.new(:field1 => csv[0], :field2 => csv[1]) end end
I have a feeling I would be better off using collect somehow rather than pushing each Line onto the array but I can’t work out how to do it.
Can anyone show me how to do it or is it perfectly fine as it is?
Edit: I should have made it clear that I’m not actually going to use this code in production, it’s more to get used to the constructs of the language. It is still useful to know there are libraries to do this properly though.
Here’s a (possibly wild) idea, use the Struct class instead of rolling your own simple POD class. But what you want from this is to have a constructor that accepts all of the arguments that could be generated from the file data.
Then at the core of the algorithm you want something like:
or being a bit more concise and functional-like:
To be honest I haven’t used the Struct class much, but I should be, and I will probably refactor stuff already written to use it. It allows you to access the variables by their names like:
The Ruby Struct class.
So to actually answer your question, and looking above at the code, I would say it would be much simpler to use collect/map to perform the computation. The map function together with inject are very powerful and I find I use them quite frequently.