回答編集履歴

1 内容修正

kazto

kazto score 5621

2018/04/19 14:02  投稿

splitせずに比較でいかがでしょうか。
追記:  
入力をタブ区切りに、出力をCSV形式にしました。  
```Ruby
irb(main):001:0> data = File.open("sample.csv").readlines.map{|v| v.chomp.split(",")}
=> [["1|abc2|1", "1", "2"], ["1|abc2|3", "2", "3"], ["1|abc2|2", "3", "3"], ["1|abc1|1", "4", "4"], ["1|abc1|2", "5", "2"], ["2|abd1|2", "7
, "5"], ["2|abd1|1", "3", "3"], ["3|acd2|1", "4", "2"]]
irb(main):002:0> data.sort{|a, b| a[0] <=> b[0]}
=> [["1|abc1|1", "4", "4"], ["1|abc1|2", "5", "2"], ["1|abc2|1", "1", "2"], ["1|abc2|2", "3", "3"], ["1|abc2|3", "2", "3"], ["2|abd1|1", "3
, "3"], ["2|abd1|2", "7", "5"], ["3|acd2|1", "4", "2"]]
irb(main):003:0> require 'pp'
=> true
irb(main):004:0> pp data.sort{|a, b| a[0] <=> b[0]}
[["1|abc1|1", "4", "4"],
["1|abc1|2", "5", "2"],
["1|abc2|1", "1", "2"],
["1|abc2|2", "3", "3"],
["1|abc2|3", "2", "3"],
["2|abd1|1", "3", "3"],
["2|abd1|2", "7", "5"],
["3|acd2|1", "4", "2"]]
```
data = File.open("sample.bl6").readlines.map{|v| v.chomp.split("\t")}
data.sort!{|a, b| a[0] <=> b[0]}
# CSVクラスを使わず
File.open("result.csv", "w") do |fh|
 data.each do |line|
   fh.puts line.join(",")
 end
end
# CSVクラス使って。どちらでもお好きな方で。
CSV.open("result.csv","w") do |fh|
data.each do |line|
  fh << line
end
end
```

思考するエンジニアのためのQ&Aサイト「teratail」について詳しく知る