LoginSignup
119

More than 5 years have passed since last update.

CSV を文字コード変換しつつロード

Posted at
CSV.foreach(filename, encoding: "Shift_JIS:UTF-8") do |row|
  # …
end

だが、未定義文字があるとエラーに。

Kernel#open だと

open(filename, "rb:Shift_JIS:UTF-8", undef: :replace) do |f|
  # …
end

のように、String#encode と同じオプションが渡せるが、CSV ではここにオプションを渡すすべはない。

よって Kernel#open と併用する。

open(filename, "rb:Shift_JIS:UTF-8", undef: :replace) do |f|
  CSV.new(f).each do |row|
    # ...
  end
end

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
119