gpt4 book ai didi

ruby - 对范围数组进行排序

转载 作者:数据小太阳 更新时间:2023-10-29 07:56:21 28 4
gpt4 key购买 nike

如何对范围数组进行排序

ranges = [Range.new(0, 3, true), Range.new(3, 5, true), Range.new(5, 7, true), Range.new(7, 9, true), Range.new(9, 11, true), Range.new(11, 100, true)]
ranges.sort
=> ArgumentError: comparison of Range with Range failed
from (irb):7:in `sort'
from (irb):7
from /Users/praveena/.rvm/rubies/ruby-2.0.0-p247/bin/irb:16:in `<main>'

但是当我尝试

2.0.0p247 :022 > (3...4) <=> (4...8)
=> nil
2.0.0p247 :023 > (3...4) <=> (1...2)
=> nil

我错过了什么吗?

最佳答案

似乎 range 有一个实现 <=> ,但并不完整。让我们检查一下:

> Range.new(3,4) <=> Range.new(3,4)
=> 0
# It seems that it correctly identify when the two are equals

> Range.new(3,4) <=> Range.new(4,4)
=> nil
# But it seems that it fails to fail when both are different!

此方法在 Range 中定义因为它实际上定义了on the Object class (!!!),因此每个对象都定义了这个方法,但这并不意味着它有效。实际上范围的实现是默认的。让我们检查一下:

# lets define a dummy class
class A
end
=> nil

# and create an object
a = A.new
=> #<A:0x9b1d998>

# can correctly identify when equal
a <=> a
=> 0

# but invalid answer when not equal!
a <=> 1
=> nil

此时,您应该了解代码中发生了什么。

range 没有规范的 <=> 是完全可以理解的方法,因为没有更大范围的数学定义(据我所知),也没有常识定义。

关于ruby - 对范围数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18498738/

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