程序应该只生成唯一的飞机,它重复元素数组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=planes.uniq没有帮助
    break if models.length == planes.length
end

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

最佳答案

除非另有规定,否则没有两个对象是相同的:

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

因此,对于#uniq来说,所有150个Airplane实例都是唯一的,没有重复的。
解决这个问题的最简单方法是为#uniq提供唯一性标准:
planes.uniq(&:model)

另一种方法是定义“duplicate”对于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

然而,这种解决方案将使同一型号的两架飞机在所有情况下都是同一架飞机,这可能会在其他地方产生意想不到的后果。

关于ruby - ruby 数组中的唯一对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57815458/

10-12 13:10