Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.ruby > #7145

Re: How do i strip CSV's "Cell" designation when migrating to YAML

From "WJ" <w_a_x_man@yahoo.com>
Newsgroups comp.lang.ruby
Subject Re: How do i strip CSV's "Cell" designation when migrating to YAML
Date 2015-10-14 13:50 +0000
Organization A noiseless patient Spider
Message-ID <mvlmi7$qv4$1@dont-email.me> (permalink)
References <374b5041-0d3d-4c15-a3f1-d19d49d1f1f1@googlegroups.com> <43c1f51a-a977-4030-83df-9feaca285513@googlegroups.com> <f79e57b2-640b-453c-8b2c-8c88ffa33161@googlegroups.com>

Show all headers | View raw


samtreweek@gmail.com wrote:

> require 'csv'
> require 'yaml'
> 
> csv  = CSV.parse("test.csv", :headers => true)
> data = csv.each_with_index.map do |row, index|
>   clean_row = row[0].split(",").map {|r| r.to_s}
>   if index == 0
>     @header = clean_row
>     next
>   end
>   Hash[@header.zip(clean_row)]
> end

Another way:

"test.csv" contains:

Name,age,sex
Tom,33,M
Bill,22,M


require 'csv'

lines = CSV.readlines("test.csv")
header = lines.shift
data = lines.map{|rec| Hash[ header.zip rec ]}

 ===>

[{"Name"=>"Tom", "sex"=>"M", "age"=>"33"},
 {"Name"=>"Bill", "sex"=>"M", "age"=>"22"}]

Back to comp.lang.ruby | Previous | NextPrevious in thread | Find similar


Thread

How do i strip CSV's "Cell" designation when migrating to YAML lfast1234@gmail.com - 2013-06-20 17:47 -0700
  Re: How do i strip CSV's "Cell" designation when migrating to YAML lfast1234@gmail.com - 2013-06-21 06:50 -0700
    Re: How do i strip CSV's "Cell" designation when migrating to YAML samtreweek@gmail.com - 2015-10-02 08:55 -0700
      Re: How do i strip CSV's "Cell" designation when migrating to YAML "WJ" <w_a_x_man@yahoo.com> - 2015-10-14 13:50 +0000

csiph-web