tags:

views:

80

answers:

3

Hi,

I've got a weird issue with Ruby. I want to read data from a file and put the data then into an array. The weird thing is, it's working in another script which does basically, the same thing.

quoteArray = []
quoteFile = File.new("quotes.txt", "r") or die "Unable to open file..."
quoteFile.each_line { |line| quoteArray.push line }
puts quoteArray[0]

All I get out of this is an array with one element where the whole text file is in. What's wrong? Is it my machine? The text file? Any ideas?

Thanks in advance

A: 

You are printing quoteArray[0]. Try printing quoteArray.inspect and see what you get.

inspect give me one looong string with some \r in them. I was assuming it's somehow related to wrong line endings. Do you know what I should do now?
A: 

It works fine for me. Make sure that your text file has multiple lines in it and not just a one single big line.

nas
As I'm not sure if my file is valid enough I've uploaded it so that you can have a look at it by yourself. http://dl.dropbox.com/u/6102/tmp/quotes.zip
Your text file doesnt have line feed character instead it has carriage return guess that's why it was getting the whole file content in a single line. I see Konstantin's solution has solved the issue :)
nas
A: 
quoteFile = File.read("quotes.txt").gsub(/\n?\r/, "\n").lines.to_a
Konstantin Haase
So easy and straight forward. Thank you very much!