LoginSignup
5
4

More than 5 years have passed since last update.

Rubyハマりメモ:CSV::Tableのヘッダ名指定

Posted at

ハマったコード(の一部)

CSV::Tableを使ってヘッダ名を指定して配列を作ろうとすると中身がnilになってしまう。

read_csv.rb
person_list = CSV.table('person_list.csv', encoding: 'UTF-8:UTF-8')
id_array = person_list["id"]
name_array = person_list["name"]
console
p id_array
=> [nil,
nil,
nil,
...

解決策

ヘッダ名をStringでなくSymbolで指定しないとダメっぽかった。

read_csv.rb
person_list = CSV.table('person_list.csv', encoding: 'UTF-8:UTF-8')
id_array = person_list[:id]
name_array = person_list[:name]
console
p id_array
=> [1001,
1002,
1003,
...
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4