How to find all groups in a given layer

It is quite similiar to this question but instead of iterating through entities or components is it possible for it to work for groups too? I have got it working to iterate through groups/components however groups all returns layer0 despite setting it to a different layer in sketchup

models.definitions.each do |defn| 
    puts defn.layer.name # returns layer0 instead of tag set in sketchup
end
Sketchup.entities.select do |e|
    e.responed_to?(:definition) && e.layer == 'specific layer'
end

An alternative…

groups_by_layer = []
layername = "some_layer_name"
Sketchup.active_model.definitions.each{|d|
  next unless d.group?
  d.instances.each{|i|
    groups_by_layer << d if i.layer.name == layername
  }
}

It’s probably clear from the other replies, but the flaw in your initial snippet is that ComponentInstances or Groups can have a tag/layer, ComponentDefinitions normally do not (the GUI provides no way to assign a tag to a definition). Further, since a ComponentDefinition is not ever displayed (despite inheriting from DrawingElement), assigning it a tag will have no effect.

Also beware that if a Group has been copied, each copy may have a different tag because assigning a tag is like setting a Transformation: it does not amount to an edit of the Group itself, so does not make an instance get a unique definition.

Yes, and assigning a material to a definition also has a weird undocumented effect.

The definition material is only displayed whilst the PlaceComponent tool has a proto-instance attached to the cursor. As soon as it is placed, the instance does not inherit the definition material and usually has no material assignment.

See: