[Ruby] CSV の header を書き換えたい
CSV::HeaderConverters を利用します。
[markdown]
> * [constant CSV::HeaderConverters (Ruby 2.4.0)](https://docs.ruby-lang.org/ja/2.4.0/method/CSV/c/HeaderConverters.html)
具体的なコードとして、以下を参考にさせて頂きました。
> * [ruby – Turning spaces into underscores in CSV headers in Rails – Stack Overflow](https://stackoverflow.com/questions/35690843/turning-spaces-into-underscores-in-csv-headers-in-rails)
> * [Ruby and CSV examples](https://gist.github.com/rogerleite/6aae63c750bdc624da68)
“`ruby
CSV.foreach(
file.path,
headers: true,
header_converters: ->(h) { h.try(:downcase).try(:gsub, ‘-‘, ‘_’) },
encoding: ‘Shift_JIS:UTF-8’
) do |row|
:
処理
:
end
“`
Lambda(無名関数)を利用して、[#gsub](https://docs.ruby-lang.org/ja/2.4.0/method/String/i/gsub.html) で置き換える。
> * [Procを制する者がRubyを制す(嘘)](http://melborne.github.io/2014/04/28/proc-is-the-path-to-understand-ruby/)
> * [module function Kernel.#lambda (Ruby 2.4.0)](https://docs.ruby-lang.org/ja/2.4.0/method/Kernel/m/lambda.html)
Rails の method `#try` も利用する。
> nilでない場合にのみオブジェクトのメソッドを呼び出したい場合、最も単純な方法は条件文を追加することですが、どこか冗長になってしまいます。そこでtryメソッドを使うという手があります。tryはObject#sendと似ていますが、nilに送信された場合にはnilを返す点が異なります。
>
> [Active Support コア拡張機能 | Rails ガイド](https://railsguides.jp/active_support_core_extensions.html#try)
[/markdown]