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?

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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, that's true, but if the question is taken literally that's the only way.

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.