samayres1992
samayres1992

Reputation: 779

Parsing arrays from CSV into strings?

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]

Upvotes: 0

Views: 782

Answers (2)

Justin Ko
Justin Ko

Reputation: 46826

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 

Upvotes: 1

saihgala
saihgala

Reputation: 5774

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

Upvotes: 1

Related Questions