Read CSV-File (Comma Separated Values)

H

hu8

Hi!

First of all, im a real beginner in ruby.

How can I read data from a file? How to separate it, is my second
question.
So, i don't want to become the File from the STDIN, but to set the uri
from the file with uri = '/home/hu8/Documents/data.csv' or somthing
like this...

btw: How can I read user input, so i make:
print "Type A or B"

and then the user must type a or b and i become in a variable (like
input = user.input()?)?
Or does exists a function like the PHP-function fgetcsv()?
 
J

James Britt

Julius said:
* hu8 <[email protected]> [2005-01-30]:
^^^
You should post with a real name here.

How can I read data from a file? How to separate it, is my
second question.


begin
file = File.open('filename')
while not file.eof?
values = file.gets.split(/,/)
# do some stuff with it
end
ensure
file.close
end

You might do better to leave the hard work to ruby:

IO.readlines( 'filename' ).each{ |line|
ary_values = line.split(/,/)
# do some stuff with it
}

By using the block form you let Ruby handle the check for EOF and close
the file when done.

James
 
S

Stefan Lang

James said:
You might do better to leave the hard work to ruby:

IO.readlines( 'filename' ).each{ |line|
ary_values = line.split(,)
^^^
Shouldn't there be quotes around the comma?
line.split(',')
 
J

James Britt

Stefan said:
James Britt wrote:



^^^
Shouldn't there be quotes around the comma?
line.split(',')

Or regexp slashes, which is what I used, and which is what appears when
I view my post in my E-mail reader (Thunderbird).

line.split(/,/)

Odd.


James
 
S

Stefan Lang

James said:
Or regexp slashes, which is what I used, and which is what appears when
I view my post in my E-mail reader (Thunderbird).

line.split(/,/)

Odd.

Sorry, seems to be a bug in KNode. The slashes are actually in
the message but my KNode doesn't show them!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top