LoginSignup
0
0

More than 3 years have passed since last update.

.sort.uniq か、.uniq.sort か

Last updated at Posted at 2020-07-01

配列をソートしてユニークするのに、.uniq.sort.sort.uniq どっちが良いのか。

長いものには巻かれようと思ったものの、破壊的に実行すると、.uniq!.sort! は実行出来ないケースがある事が判明 @2.7.1

test.rb
r = {
  's' => [5,1,3,53,2],
  't' => [5,3,4,4,3,2],
}
r.each_key{|k|
  #r[k].sort!.uniq!
  r[k].uniq!.sort!
  #  => ダメ
}
p r
$ ruby test.rb
Traceback (most recent call last):
    2: from hoge2.rb:5:in `<main>'
    1: from hoge2.rb:5:in `each_key'
test.rb:7:in `block in <main>': undefined method `sort!' for nil:NilClass (NoMethodError)

.sort!.uniq! では実行出来る。

普通に、

test2.rb
a = [5,3,4,4,3,2]
#a.sort!.uniq!
a.uniq!.sort!

p a

な場合はエラーになんない。

ベンチが遅かろうと、.sort.uniq の方を使うかな1


  1. こっちの方が、シェルで馴染み深いし。 

0
0
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
0
0