1

So if a have this code:

class A
    def initialize(type)
        @type = type
    end
end

instance = A.new(2)
another_instance = A.new(1)

array = [instance, another_instance]

is there a way to check if array includes an instance of A where @type is equal to a certain value? say, 2? like the include? method but where instead of checking for an instance of a certain class, it also checks the instance variables of that class?

Matthew Flynn
  • 191
  • 1
  • 12
  • Have look at [Override == operator in Ruby](http://stackoverflow.com/questions/11186815/override-operator-in-ruby) – Wand Maker Jan 20 '16 at 08:28

2 Answers2

2

I would recommend using anattr_reader for this one unless you plan on modifying the type somewhere after (in that case use attr_accessor which is both a writer and reader)

class A
  attr_reader :type
  def initialize(type)
    @type = type
  end
end
instance = A.new(2)
another_instance = A.new(1)

array = [instance, another_instance]

array.select do |item|
  item.type == 2
end
=>[#<A:0x00000000dc3ea8 @type=2>]

Here I am iterating through an array of instances of A and selecting only the ones that meet the condition item.type == 2

Cyzanfar
  • 6,997
  • 9
  • 43
  • 81
1

You can just refer to the instance variable.

> array.any? { |item| item.is_a?(A) }
=> true
> array.any? { |item| item.instance_variable_get(:@type) == 1 }
=> true
> array.select { |item| item.instance_variable_get(:@type) == 1 }
=> [#<A:0x007fba7a12c6b8 @type=1>]

Or, use attr_accessor in your class, to make it way easier

class A
  attr_accessor :type
  def initialize(type)
    @type = type
  end
end

then you can do something = A.new(5); something.type

court3nay
  • 2,215
  • 1
  • 10
  • 15
  • You *can* use `instance_variable_get`, but you definitely shouldn't. Instance variables are private by design. If you want their value to be public, that's what `attr_reader` or `attr_accessor` is for. – Jordan Running Jan 19 '16 at 20:54
  • @Jordan, that's true, but if the question is taken literally that's the only way. – Cary Swoveland Jan 19 '16 at 21:34