0

I'm having a bit of trouble understanding how to take data from a CSV file to use elsewhere.

My code currently is only:

CSV.foreach("../../lib/modules/csv.csv") do |row|
    # use row here...

    def initialize(headers, fields, header_row = false)  
  end
end  

That is all I could really pick up from the documentation of Ruby. There doesn't seem to be any examples of how select a header then take a cell under that header?

Here's a quick mock-up of an example table if I'm not explaining this well enough:

 title  |  description  |  priority 
----------------------------------   
 story1 |    example1   |     6
----------------------------------     
 story2 |    example2   |     7
----------------------------------  
 story3 |    example3   |     8
----------------------------------  

How can I get the data to be stored in the string?:

example = column[i]

2 Answers 2

1

When getting the values from a row, you can get the value by index (as shown by Ashish). You can also get it based on the header description, which it sounds like you want.

The following examples shows how you can create an array of all of the values in the 'description' column:

all_descriptions = Array.new
CSV.foreach("test.csv", :headers=>true, :header_converters=>:symbol) do |row|
    all_descriptions << row[:description]
end  
all_descriptions
#=> ['example1', 'example2', 'example3']

As you can see, you can get the description value for each row using row[:description], where :description is the column heading turned into a symbol.

Note that if you want to store the value for later use in the loop, it would look something like:

CSV.foreach("test.csv", :headers=>true, :header_converters=>:symbol) do |row|
    example = row[:description]
    #do stuff
    if example =~ /something/
      #do other stuff
    end
end 
Sign up to request clarification or add additional context in comments.

1 Comment

Did you do a require 'csv'? The csv class is not automatically included (ie you have to manually do it).
1

You can access individual cells using index of row variable.

CSV.foreach("../../lib/modules/csv.csv", headers: true) {|row| puts "#{row[0]} - #{row[1]} #{row[2]}" }

if you set headers:true then each row is an instance of CSV::Row and first line of your csv is treated as the header row. It'll output

story1 - example1 - 6
story2 - example2 - 7
story3 - example3 - 8 

However if you set headers:false each row is an instance of Array and it'll print -

title - description - priority
story1 - example1 - 6
story2 - example2 - 7
story3 - example3 - 8

1 Comment

Thanks for the help, can you clarify a little more for me the follow: if I wanted to use example 2 within as a string how would i do that? eg string2 = x

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.