红宝石数组中的唯一对象

时间:2019-09-06 03:46:55

标签: ruby

该程序应该只生产唯一的飞机,它重复元素数组。 uniq方法无济于事。

class Airplane

    attr_accessor :model        

    def initialize(model) 
        @model = model
    end
end

models  =   [ "Boeing 777-300ER",
              "Boeing 737-800",
              "Airbus А330-200", 
              "Airbus А330-300",
              "Airbus А321",
              "Airbus A320",
              "Sukhoi SuperJet 100"]
planes = []

150.times do

    model = models[rand(0..6)]
    plane = Airplane.new(model)

    planes << plane 

在这里尝试#飞机= planes.uniq没有帮助

    break if models.length == planes.length
end

# result
planes.uniq.each do |plane|   # <<<< uniq doesn't help
    puts "Model: #{plane.model}"
end

2 个答案:

答案 0 :(得分:8)

除非另有说明,否则没有两个对象相同:

Object.new.eql?(Object.new)
# => false

因此,就#uniq而言,所有150个Airplane实例都是唯一的,没有重复。

解决此问题的最简单方法是为#uniq提供唯一性标准:

planes.uniq(&:model)

另一种方法是定义“重复”对Airplane类的含义:

class Airplane
  attr_accessor :model        

  def initialize(model) 
    @model = model
  end

  def ==(other)
    other.class == self.class && other.model == self.model
  end

  alias_method :eql?, :==

  def hash
    self.model.hash
  end
end

但是,在所有情况下,此解决方案将使两架相同型号的飞机同一架飞机,这可能会在其他地方带来意想不到的后果。

答案 1 :(得分:0)

您正在比较一个类的对象,每个对象都不同,即使它们是相同的实例类型。您可以通过为类定义比较方法来覆盖此行为

class Aeroplane
    def ==(o)
      o.class == self.class && o.model == model
    end
end