首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

SortedSet

Parent:Set

SortedSet实现了一个Set,它可以确保其元素在迭代时按排序顺序(根据它们的#<=>方法的返回值)生成。

所有添加到SortedSet的元素都必须对<=>方法进行响应以进行比较。

此外,所有元素必须相互可比:el1 <=> el2不能返回任何元素el1和el2的nil,否则在迭代SortedSet时将引发ArgumentError。

代码语言:javascript
复制
require "set"

set = SortedSet.new([2, 1, 5, 6, 4, 5, 3, 3, 3])
ary = []

set.each do |obj|
  ary << obj
end

p ary # => [1, 2, 3, 4, 5, 6]

set2 = SortedSet.new([1, 2, "3"])
set2.each { |obj| } # => raises ArgumentError: comparison of Fixnum with String failed

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com