How can I get count of components in my file skp in ruby api?

Hello guys,

I need to get a count of components like this picture must get 4 components.

I tried this statement :

entities.count

But it doesn’t return the right value.

E.g. this will count of the component instances in a current drawing context:

model = Sketchup.active_model
entities = model.active_entities
instances_count = entities.grep(Sketchup::ComponentInstance).size
1 Like

Thank you very much @dezmo :slight_smile:

1 Like

You can also count for all nested, recursively:

def get_instances(ents, instances = [])
  ents.each{|e|
    case e
    when Sketchup::Group
      get_instances(e.entities, instances)
    when Sketchup::ComponentInstance
      instances<<e
      get_instances(e.definition.entities, instances)
    end
  }
  instances
end

model = Sketchup.active_model
entities = model.active_entities
all_instances_count = get_instances(entities).size
2 Likes

… or do a one-liner …

Sketchup.active_model.definitions.count {|cdef| cdef.count_used_instances }
3 Likes