Move all entities to new group

Hello, I would like to create a ruby script that takes every entity in the scene and puts them in a new group.

I have

group = model.entities.add_group(Sketchup.active_model.selection)

working to add all selected objects to a new group. But I want to add all scene objects.

I tried:

group = model.entities.add_group(Sketchup.active_model.entities)

and

group = model.entities.add_group(Sketchup.active_model.active_entities)

and even:

entities = Sketchup.active_model.active_entities
entitiesArray = Array.new(entities.count)
entities.each{ |entity| entitiesArray.push(entity) }
group = model.entities.add_group(entitiesArray)

But I get:

TypeError: wrong argument type (expected Sketchup::Entity)>

Any idea what I am doing wrong?

The API docs misstate the acceptable arguments to add_group. It can be an Entity, a list of Entities, or an array of Entities. The model’s Entities collection is none of those. So,

In your first two examples, you need to convert the entities collection into an array using #to_a

group=model.entities.add_group(Sketchup.active_model.entities.to_a)

In third example, you have created an Array with entities.count nil objects in it and then pushed Entities onto the end of it. Push appends without changing the original contents, so all those nils are still present. To create an empty array, use

entitiesArray=[]

Yes, you must turn the ‘entities’ into an Array using .to_a

The other issue is that you cannot use:

some_entities_context.add_group(array_of_entities)

IF the some_entities_context if not the Sketchup.active_model.active_entities AND the array_of_entities is also entirely composed of ‘entities’ in that exact same context.

A sure-fired way to make a Bugslplat is to ‘cross-thread’ the entities_context and the listed_entities

The normal way to use add_group() is NOT to make a new group from [‘pre]selected’ entities; but rather to make a new empty group and then add your new entities directly into it…

new_group = some_entities_context.add_group()
new_group.entities.add_line(pt1, pt2)

And so on…
NOTE: you need to avoid making the empty group too soon, because SketchUp’s “Garbage Collection” deletes any empty definitions [groups/components], so try to make it and add entities into its entities context shortly afterwards…

Sometines we insert a temporary CPoint into the new group to keep it from getting GC’d too soon. (Then remove it at the end of your code that adds objects to the new group.)