排序字符串在Ruby中的数组 [英] Sorting an array of strings in Ruby
问题描述
我已经在Ruby中得知两数组排序方法:
I have learned two array sorting methods in Ruby:
array = ["one", "two", "three"]
array.sort.reverse!
或
array = ["one", "two", "three"]
array.sort { |x,y| y<=>x }
和我不能够在两者之间进行区分。哪种方法更好,究竟如何在执行不同?
And I am not able to differentiate between the two. Which method is better and how exactly are they different in execution?
推荐答案
这两条线做同样的(创建新阵列,这是反向排序)。主要论点是关于可读性和性能。 <!code> array.sort.reverse 比 {的Array.sort更具可读性| X,Y | Y'LT =方式&gt; X}
- 我认为,我们可以在这里同意
Both lines do the same (create a new array, which is reverse sorted). The main argument is about readability and performance. array.sort.reverse!
is more readable than array.sort{|x,y| y<=>x}
- I think we can agree here.
有关业绩的一部分,我创建了一个快速基准脚本,它给我的系统上的以下(红宝石1.9.3p392 [x86_64的Linux的]
):
For the performance part, I created a quick benchmark script, which gives the following on my system (ruby 1.9.3p392 [x86_64-linux]
):
user system total real
array.sort.reverse 1.330000 0.000000 1.330000 ( 1.334667)
array.sort.reverse! 1.200000 0.000000 1.200000 ( 1.198232)
array.sort!.reverse! 1.200000 0.000000 1.200000 ( 1.199296)
array.sort{|x,y| y<=>x} 5.220000 0.000000 5.220000 ( 5.239487)
运行时间为基准脚本的多个执行pretty不变。
Run times are pretty constant for multiple executions of the benchmark script.
array.sort.reverse
(带或不带!
)比办法更快{的Array.sort | X,Y | Y'LT; = GT; X}
。因此,我建议。
array.sort.reverse
(with or without !
) is way faster than array.sort{|x,y| y<=>x}
. Thus, I recommend that.
下面是脚本作为参考:
#!/usr/bin/env ruby
require 'benchmark'
Benchmark.bm do|b|
master = (1..1_000_000).map(&:to_s).shuffle
a = master.dup
b.report("array.sort.reverse ") do
a.sort.reverse
end
a = master.dup
b.report("array.sort.reverse! ") do
a.sort.reverse!
end
a = master.dup
b.report("array.sort!.reverse! ") do
a.sort!.reverse!
end
a = master.dup
b.report("array.sort{|x,y| y<=>x} ") do
a.sort{|x,y| y<=>x}
end
end
这篇关于排序字符串在Ruby中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!