5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

csvをrubyでユニークする.

Last updated at Posted at 2016-07-15

##はじめに
rubyでスクレイピングしてきてcsvに吐き出したのだが、電話番号やら店舗名やらで重複している。そこで、二重配列をユニークする必要があった。

スクレイピングしてきたcsvのカラムは
[大カテゴリ、中カテゴリ、少カテゴリ、店名、住所、電話番号]
という感じ。

uniqメソッドにブロックを渡して解決

例えばcsvはこんな感じ

csv1 = [["大カテゴリ","中カテゴリ","少カテゴリ","店名","住所","電話番号"]
        ["A","B","C","D","E","03-0000-0000"]
        ["F","B","E","R","A","03-0000-1232"]
        ["Y","T","G","H","C","03-0000-0000"]]

電話番号でユニークしたいとすると、
uniq後はこうなってほしい

csv2 = [["大カテゴリ","中カテゴリ","少カテゴリ","店名","住所","電話番号"]
        ["A","B","C","D","E","03-0000-0000"]
        ["F","B","E","R","A","03-0000-1232"]

こうすればできたよ。

csv2 = csv1.uniq{|item| item[5]}

uniqメソッドのリファレンス

5
2
1

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?