1

Ruby 1.8 と FasterCSV を使用しています。

私が読んでいるcsvファイルには、いくつかの繰り返し列があります。

| acct_id | amount | acct_num | color | acct_id | acct_type | acct_num |
|     345 |  12.34 |      123 |   red |     345 | 'savings' |      123 |
|     678 |  11.34 |      432 | green |     678 | 'savings' |      432 |

...等

私はそれを次のように要約したいと思います:

| acct_id | amount | acct_num | color | acct_type |
|     345 |  12.34 |      123 |   red | 'savings' |
|     678 |  11.34 |      432 | green | 'savings' |

これを行う一般的な方法はありますか?

現在、私の解決策は次のようなものです:

headers = CSV.read_line(file)
headers = CSV.read_line # get rid of garbage line between headers and data
FasterCSV.filter(file, :headers => headers) do |row|
  row.delete(6) #delete second acct_num field
  row.delete(4) #delete second acct_id field

  # additional processing on the data
  row['color'] = color_to_number(row['color'])
  row['acct_type'] = acct_type_to_number(row['acct_type'])
end
4

1 に答える 1

1

ハードコーディングされた削除を取り除きたいと仮定すると

  row.delete(6) #delete second acct_num field
  row.delete(4) #delete second acct_id field

で置き換えることができます

row = row.to_hash

これにより、重複が破壊されます。投稿されたコードの残りの部分は引き続き機能します。

于 2011-04-05T20:03:42.657 に答える