Group Attributes and Ruby Method #include?

I have a collection of groups and for one of the groups I have assigned the attributes cat, dog and rabbit.

value = ["cat", "dog", "rabbit"]
sel = Sketchup.active_model.selection
obj = sel.first
obj.set_attribute( "PMC", "Pets", value )

If I select this group, I can hide it:

pets = obj.get_attribute("PMC", "Pets")
if pets.include?("cat")
	obj.hidden = true

If none of the groups are selected I am attempting to interrogate all the groups, using the following, to hide the group with the attribute cat:

group_definitions = Sketchup.active_model.definitions.find_all{|e| }
groups = group_definitions.collect {|e| e.instances }.flatten
groups.each{ |e|
	pets = e.get_attribute("PMC", "Pets")
  	if pets.include?("cat") 
    	e.hidden = true

But I am getting the error: #<NoMethodError: undefined method `include?' for nil:NilClass>

EDIT: edited that last section of code to replace

if value.include?("cat")
if pets.include?("cat")

If there is no attribute that matches the given name, #get_attribute method returns nil.

So if the ‘pets’ is nil (as the error suggesting) there is no method include?' for nil`

You need to check if pets get value or not. E.g.:

if pets && pets.include?("cat")
1 Like

Thanks dezmo !

It’s obvious when it’s pointed out :person_facepalming:

If one is only working with Ruby 2.5 and later (SketchUp 2019 and later?) you can use what’s often referred to as the ‘Safe Navigation Operator’, which is &.. It returns nil if the caller is nil. So

if pets && pets.include?("cat")

is equivalent to:

if pets&.include?("cat")