1

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:

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.

3
  • If you need to see whether something is in an array, you need to reconsider whether an array is the appropriate structure. Arrays are great for storing things you want to access in a particular order, either as a stack or a queue, but as they grow the time it takes to look through them grows and grows. Instead, if you want to know if something exists consider a Hash, or some form of a tree that allows very fast lookups regardless of the order. Commented Oct 26, 2015 at 18:06
  • I'm aware of the benefits of a hash and other structures, however the task I am coding only has arrays of a maximum of 5 elements so efficiency isn't a big issue here. Commented Oct 26, 2015 at 18:10
  • Efficiency is ALWAYS a concern. Do an inefficient operation enough times and it has an impact. Commented Oct 26, 2015 at 18:27

3 Answers 3

1

So the proper way to ensure object equality is to implement #== and #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
Sign up to request clarification or add additional context in comments.

1 Comment

That seems to work on all cases and allows me to use the include? method as before without any extra work. Thanks!
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.