gpt4 book ai didi

ruby - <=> 和 - 在 sort 方法的 block 中有什么区别?

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:03 24 4
gpt4 key购买 nike

我有一个这样的数组:

my_array = [1,3,5,5,6,7] 

从大到小排序。我这样做:

  1. my_array.sort { |a,b| b <=> a }
  2. my_array.sort { |a,b| b - a }

两者都返回相同的东西:[7,6,5,5,3,1] .谁能解释一下这两者之间的区别?

最佳答案

document状态:

sort → array sort { |a, b| block } → array Returns an array containing the items in enum sorted, either according to their own <=> method, or by using the results of the supplied block. The block should return -1, 0, or +1 depending on the comparison between a and b. As of Ruby 1.8, the method Enumerable#sort_by implements a built-in Schwartzian Transform, useful when key computation or comparison is expensive.

所以当区 block 的评估值不是-1时,官方没有提及, 0 , 或 1 .如果你所做的有效,那么它可能是在负数被视为 -1 的原则下工作的。和正数被视为 1 .如果是这样,那就没有区别了。但是,由于没有官方说明,我认为使用 {|a, b| b <=> a} 更安全。

关于ruby - <=> 和 - 在 sort 方法的 block 中有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26408512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com