Matthew Flynn
Matthew Flynn

Reputation: 191

check if array includes an instance with a certain value for an instance variable Ruby

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?

Upvotes: 1

Views: 331

Answers (2)

Cyzanfar
Cyzanfar

Reputation: 7136

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

Upvotes: 2

court3nay
court3nay

Reputation: 2365

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

Upvotes: 1

Related Questions