Which is better, .uniq.sort
or .sort.uniq
, to sort and make the array unique?
I thought it would be wrapped around a long one, but when I executed it destructively, it turned out that there were cases where .uniq! .Sort!
Could not be executed @ 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!
# =>No good
}
p r
python
$ 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)
You can do it with .sort! .uniq!
.
Normally,
test2.rb
a = [5,3,4,4,3,2]
#a.sort!.uniq!
a.uniq!.sort!
p a
If so, there is no error.
Even if the bench is slow, I wonder if I will use .sort.uniq
[^ 1]
[^ 1]: This one is more familiar with the shell.
Recommended Posts