Reputation: 191
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
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
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