Traversing through Entities in a Group

We’ve been here and done this question / exercise already.

Firstly, in Ruby whenever dealing with collections (Arrays, Hashes, etc.) be sure to consult the Enumerable module for all it’s nifty methods which are mixed into all the collection classes (as well as many of the SketchUp API’s collection classes.)

Secondly, the previous posts in the Selecting Specific Entity, Group or Component (By Name) thread …

Thirdly the examples show exact matches using the == method, you’ll likely want to use regular expression to find matches to substrings or start strings. (Ruby 2.0 added some methods to the String class for #start_with?)

Reg expressions … (lowercase i after expression is case insensitive)

HAS_DOOR = /door\d+/i # contains "door" followed by 1 or more digit characters

… or …

BEGINS_DOOR = /\Adoor\d+/i # Starts with "door" followed by 1 or more digit characters

… then later in your code …


… or …

doors = wall.entities.grep(Sketchup::Group).find_all {|grp| =~ BEGINS_DOOR }

You do not want to use literal inside a loop as it will create an new Regexp object each time through the loop.) The references do not absolutely have to be a constant if they are only needed on occasion. They could be local references inside a method that get cleaned up when the method ends.

1 Like