Add components to another component (nested components)

I’m using this code to create a 2D grid using components.
I create a group, define a face inside it, transform it into a component and then I copy it several times.
I would like to define a new component and add all the other components.
At the end there should be a component named “XX” that contains the other components.
How can I do that?

# Creates a 2D grid using components

n = 20 #repetitions X axis
s = 2 #repetitions Y axis

@width = 1.m #width of box
@long = 2.m #length of box
@thick = 40.mm #thickness of box
@spacing = 20.mm #spacing between boxes

@distX = @width + @spacing #pitch X axis
@distY = @long + @spacing #pitch Y axis

entities = Sketchup.active_model.entities
group = Sketchup.active_model.entities.add_group #create a group in entities
face = group.entities.add_face [0,0,0],[@width,0,0],[@width,@long,0],[0,@long,0] #define face inside group
face.pushpull (-1*@thick) #make the box
comp = group.to_component #convert group into component
comp.name = @long.to_s + " x " + @width.to_s 

(0..n-1).each { |i| #copy X axis
  (0..s-1).each { |j| #copy Y axis
    if !((i==0) && (j==0)) #don't copy yourself
       transformation = Geom::Transformation.new([i*@distX,j*@distY,0])
       componentinstance = entities.add_instance(comp.definition, transformation)
    end
  }
}
entities = Sketchup.active_model.entities
group = entities.add_group

(Don’t repeat yourself. And you want to use the very same entities reference that was returned the first time and no other.)

comp.name = "#{@long} x #{@width}"

(With string interpolation you have less plusses and quotes.)


When scripting and using the API, we think in a different paradigm than when modeling with the mouse. We do not first draw faces and then “package” them in a new component, but we create the component definition and then draw faces inside.

Instead of creating a group (instance), then converting it to a component instance and taking its definition, you can go top down and create the definition first.

new_definition = model.definitions.add('ComponentDefinition2')
# Now draw inside, add_face etc. or add_instance:
new_definition.entities.add_instance(old_definition, transformation)