Skip to content

Instantly share code, notes, and snippets.

@k2works
Created December 24, 2014 02:36
Show Gist options
  • Save k2works/1585fce9e2cf1bb65037 to your computer and use it in GitHub Desktop.
Save k2works/1585fce9e2cf1bb65037 to your computer and use it in GitHub Desktop.
ヘッダ行を考慮してCSVを読み込む
# coding: utf-8
require 'csv'
data = <<EOS
name,age,gender
alice,14,female
bob,32,male
carol,17,female
EOS
CSV.parse(data, headers: :first_row) do |row|
# ヘッダ名をキーにしてハッシュのようにアクセスできる
name = row['name']
age,gender = row.values_at('age','gender')
puts "#{name} is #{gender} {#age}"
end
# >> alice is female {#age}
# >> bob is male {#age}
# >> carol is female {#age}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment