1
votes

I have simple csv file that has the following header: 'NYC'. I use CSV fetch method: http://ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/CSV/Row.html#method-i-fetch

the problem is that when I use fetch with 'NYC' it works properly but when I use fetch with 'nyc' it returns:

KeyError: key not found: nyc

How can I solve this problem?

1

1 Answers

3
votes

There's an option :header_converters. You can set it to:

  • :downcase Calls downcase() on the header String.
  • :symbol The header String is downcased, spaces are replaced with underscores, non-word characters are dropped, and finally to_sym() is called.

Example:

require 'CSV'

CSV.parse("NYC\nfoo", headers: true, header_converters: :symbol) do |row|
  row[:nyc] #=> "foo"
end