Ruby:想要一个保存顺序的类似Set的对象
发布时间:2020-12-16 19:33:09 所属栏目:百科 来源:网络整理
导读:…或者是一个防止重复输入的数组. Ruby中是否存在某种对象: 响应[],[] =和 默默地删除重复的条目 是可枚举的(或至少支持find_all) 保留插入条目的顺序 ? 据我所知,一个数组支持第1,3和4点;而Set则支持1,2和3(但不支持4).并且SortedSet不会这样做,因为我的
…或者是一个防止重复输入的数组.
Ruby中是否存在某种对象: >响应[],[] =和<< 据我所知,一个数组支持第1,3和4点;而Set则支持1,2和3(但不支持4).并且SortedSet不会这样做,因为我的条目没有实现< =>. 解决方法
据我所知,没有一个,并且其数学性质的Set意味着无序(或者至少,在实现上,意味着不保证顺序 – 事实上它通常被实现为哈希表,所以它确实搞乱了顺序).
但是,直接扩展数组或将其子类化为执行此操作并不困难.我刚试了一下这个有效: class UniqueArray < Array def initialize(*args) if args.size == 1 and args[0].is_a? Array then super(args[0].uniq) else super(*args) end end def insert(i,v) super(i,v) unless include?(v) end def <<(v) super(v) unless include?(v) end def []=(*args) # note: could just call super(*args) then uniq!,but this is faster # there are three different versions of this call: # 1. start,length,value # 2. index,value # 3. range,value # We just need to get the value v = case args.size when 3 then args[2] when 2 then args[1] else nil end super(*args) if v.nil? or not include?(v) end end 似乎涵盖了所有的基础.我使用了OReilly的方便的Ruby Cookbook作为参考 – 他们有一个“确保排序数组保持排序”的配方,这是类似的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |