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

…或者是一个防止重复输入的数组.

Ruby中是否存在某种对象:

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

据我所知,一个数组支持第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作为参考 – 他们有一个“确保排序数组保持排序”的配方,这是类似的.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...