Rails Snippets

On February 26, 2009, in Development, Ruby and Rails, by tov

OK, this is more Ruby than Rails but nevertheless helpful…

If you come from a Perl background you will be surprised that in Ruby an array is definitively not a list. So if you want to pass a list of elements to a method that you have stored in an array, you may want to use the following idiom:
list = []
lines = File.readlines("FILENAME")
lines.each do |line|
list.push(Result.new(*line.split(" ")))

The *line.split(" ") creates an element list out of the array that the split command has created.

I fear a real Rubyist would have done it in a different way but OK.

P.S. Does someone know what I’m doing wrong with the code formatting in WordPress? I’m quite sure to have included whitespaces in the code above…

Tagged with: