I’m frankly quite confused what you are trying to achieve. I know it has to do with counting component instances but do you want to:
a) count the number of instances of a certain definition within another certain definition,
b) count the number of instances of a certain definition within the selection,
c) count the number of instances of a certain definition within another certain definition, within the selection or
d) something else.
Also note that there can be several instance counts of the same definition. Imagine you create a definition named “Bed” and inside it create another definition called “Pillow” and then copy the component “Bed” so you have to instances of it. Technically there is still only one instance of the component named “Pillow”, the one that resides in the “Bed” definition. pillow_definition.instances.size returns 1. Still you can visually see 2 pillows in the model and when selecting the pillow Entity Info will report 2 instance. This is because there are 2 instance paths, one going to the first Bed instance and one going through the second Bed instance, both leading to the same single Pillow instance. If you want to count instances, which count are you interested in?
As Kirrill mentioned the select method has nothing to do with adding entities to the selection (highlight them and let the user interacts with them). The select method is a Ruby core method that exists in all Ruby environments, even outside of SketchUp. The select method is filter out only the elements in a collection that matches a certain condition.
Instead of writing this:
matches = []
my_array.each do |element|
matches << element if some_condition
end
matches
you can write this:
my_array.select { |e| some_condition }
It means the same but the latter is easier top read which makes the code easier to work with easier to dind bugs in and easier to add new features to.
Regarding code readability if would help drastically if you payed more attention to indentation. Indent with two spaces, only increase indentation when a new code block is opened (on if, unless, def, do, { etc) and only decrease indentation when a code block is closed (end and }). If a line neither opens or closes code blocks it should line up with the line above.
In this code I struggle to read that the reference to e in “e.erase! unless e.visible?” is the e defined in “grep(Sketchup::ComponentDefinition).each do |e|” becase it looks like the code block opened by do is already closed at erase!.
Without being able to parse the code I can’t say if it works.