def uniq_array
~ 配列にセットする処理 〜
ary.uniq!
end
上記のような、取得した値を配列にセットして最後に重複を削除して返す処理を書いてたんですが、どうもある場合に nil
が返ってきていました。
マニュアルを見てみると原因が書いてありました。
uniq は配列から重複した要素を取り除いた新しい配列を返します。 uniq! は削除を破壊的に行い、削除が行われた場合は self を、 そうでなければnil を返します。
確認してみます。
[1] pry(main)> ary1 = %w(1 2 3)
=> ["1", "2", "3"]
[2] pry(main)> ary2 = %w(1 1 3)
=> ["1", "1", "3"]
[3] pry(main)> p ary1.uniq
["1", "2", "3"]
=> ["1", "2", "3"]
[4] pry(main)> p ary2.uniq
["1", "3"]
=> ["1", "3"]
[5] pry(main)> p ary1.uniq!
nil
=> nil
[6] pry(main)> p ary2.uniq!
["1", "3"]
=> ["1", "3"]
重複が無かった場合に 破壊的メソッドは nil
が返ってます。
そもそも、配列を返してを使うんだから、破壊的メソッド uniq!
を使う必要はなかったんですが。。。