6

input file looks like:

dog,white,male
cat,purple,female
rat,gray,male

and i want to go through and do things with that data, line by line.

File.open("animals.csv")
  while file has next line
    currentline = array with each cell being an entry in the array
    if currentline[0] == dog
      put "dogs are cool"
    end
    put "your animal is a " + currentline[0]
  end

You get the idea, right? I want to manipulate data line with ifs and whatnot and print it all out at the end.

Thanks

3 Answers 3

9
require 'csv'
CSV.foreach("animals.csv") do |row|
  puts 'dogs are cool' if row[0] == 'dog'
  puts "your animal is a #{row[0]}"
end
Sign up to request clarification or add additional context in comments.

2 Comments

I'm using this with ActiveRecord create and get : thread failed: inotify event queue has overflowed , any ideas?
Not really. Try posting it as a new question with more details
2

Ruby includes a CSV class that makes parsing and working with CSVs even simpler. Check out: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html

Comments

0

You can use the magic of blocks to clean up your line reading code quite a bit. The code below will close your handle for you and also get each line one at a time without too much extra buffering.

IO.foreach("animals.csv") do |line|
   parts = line.split(',')
   ...
end

As noted there is a CSV library, but if your data is not complicated, doesn't have embedded commas and whatenot, the above is reasonable.

Also note that you want to compare to the string "dog" rather that some variable named dog. To make a string enclose the letters in quotes, otherwise ruby will think its a variable or maybe a method call.

if currentline[0] == "dog"

1 Comment

Why reinvent the wheel? You have the CSV class, use that. "if your data is not complicated" is not a valid reason, IMO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.