Select by entityID

Trying to get a selection by entityID, not sure what I am not doing…

#entityID is 725, none of these select the entity, what am I doing wrong?


What I am trying to do is select an array of entities by entityID
Newbie so thanks for any help.

For a single ID, the 1st step is finding the entity that matches your ID.

model = Sketchup.active_model
ents = model.entities

… then using Enumerable#find

found = ents.find {|e| e.entityID == 725 }

If the entity was found, then found will be it’s reference, and nil if not found.

If looking for multiple (Drawingelement) Entity objects, that are say hidden, you can use Enumerable#find_all

found = ents.find_all {|e| e.hidden? }

With this filter method the return is always an array, which might be empty if no entity matched the search block.

Okay? Now, for multiple IDs, you will need to define an array of the IDs to search for.

targets = [725, 726, 832, 901]

Then test if each entity’s id is included in the array …

found = ents.find_all {|e| targets.include?(e.entityID) }

(There might be another search algorithm that stops iterating once all targets are found, but for this tutorial we’ll use the simple brute force iterator method.)

Once you have the found entity array, just pass it as an argument to the Selection#add method (as long as it’s not nil) …

model.selection.add(found) if found

But keep in mind that some API methods will return non-Drawingelement objects which the Selection does not like.


The #add method actually wants Sketchup::Drawingelement subclass objects, so we must filter other types out …

stuff = instance.explode.grep(Sketchup::Drawingelement)
1 Like

Note that will search only the ents collection. If you want to search the whole model use model.find_entity_by_id:

It allows you to search multiple IDs which will be more efficient than searching one by one.


And, this method is implemented in compiled C, so it can be faster than an interpreted Ruby iterator block.

When searching multiple, a nil value is returned for those IDs not found, so it will be a safe paradigm to compact the result array before attempting to use those references. Otherwise, for example, trying to add the result array containing nil members to the model selection would cause an exception.