简体   繁体   English

查找对象是否在Ruby中的数组中?

[英]Finding if an object is in an array in Ruby?

So I thought this would be pretty basic but I'm having no luck in finding out whether an object with the same attributes as one within an array is in fact in the array. 因此,我认为这将是非常基本的,但是要找出一个与数组中具有相同属性的对象是否确实存在于数组中,我就没有运气了。 The below code returns false: 下面的代码返回false:

hand = [Card.new(:ace)]
puts("#{hand.include?(Card.new(:ace))}")

yet I can't see how I can check if the card in the hand array has the same contents of the card I provide in the include? 但我看不到如何检查手阵列中的卡是否与我在包含中提供的卡的内容相同? argument. 论点。

assuming 假设

class Card
  attr_reader :card

  def initialize(card)
    @card = card
  end
end

you can use: 您可以使用:

hand.find { |c| c.card == :ace }

find returns either first matching element or nil find返回第一个匹配元素或nil

So the proper way to ensure object equality is to implement #== and #hash 因此,确保对象相等的正确方法是实现#==#hash

class Card
  attr_accessor :card

  def initialize(card)
    @card = card
  end

  def ==(other)
    other.class == self.class && other.card == @card
  end

  alias_method :eql?, :==

  def hash
    @card.to_s.hash
  end
end

p Card.new(:ace) == Card.new(:ace)
#=> true

You would need to add a method to measure equality between cards of the card class. 您将需要添加一种方法来测量卡类的卡之间的相等性。 Your class may look like this: 您的课程可能如下所示:

class Card

  attr_reader :value

  def initialize(v)
    @value = v
  end

  def ==(other_card)
    @value == other_card.value
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM