Ruby:想要一个保存顺序的类似Set的对象

前端之家收集整理的这篇文章主要介绍了Ruby:想要一个保存顺序的类似Set的对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
…或者是一个防止重复输入的数组.

Ruby中是否存在某种对象:

>响应[],[] =和<<
>默默地删除重复的条目
>是可枚举的(或至少支持find_all)
>保留插入条目的顺序

据我所知,一个数组支持第1,3和4点;而Set则支持1,2和3(但不支持4).并且SortedSet不会这样做,因为我的条目没有实现< =>.

解决方法

据我所知,没有一个,并且其数学性质的Set意味着无序(或者至少,在实现上,意味着不保证顺序 – 事实上它通常被实现为哈希表,所以它确实搞乱了顺序).

但是,直接扩展数组或将其子类化为执行此操作并不困难.我刚试了一下这个有效:

  1. class UniqueArray < Array
  2. def initialize(*args)
  3. if args.size == 1 and args[0].is_a? Array then
  4. super(args[0].uniq)
  5. else
  6. super(*args)
  7. end
  8. end
  9.  
  10. def insert(i,v)
  11. super(i,v) unless include?(v)
  12. end
  13.  
  14. def <<(v)
  15. super(v) unless include?(v)
  16. end
  17.  
  18. def []=(*args)
  19. # note: could just call super(*args) then uniq!,but this is faster
  20.  
  21. # there are three different versions of this call:
  22. # 1. start,length,value
  23. # 2. index,value
  24. # 3. range,value
  25. # We just need to get the value
  26. v = case args.size
  27. when 3 then args[2]
  28. when 2 then args[1]
  29. else nil
  30. end
  31.  
  32. super(*args) if v.nil? or not include?(v)
  33. end
  34. end

似乎涵盖了所有的基础.我使用了OReilly的方便的Ruby Cookbook作为参考 – 他们有一个“确保排序数组保持排序”的配方,这是类似的.

猜你在找的Ruby相关文章