Sort by Component Definition Name

I have a ruby running happily that takes a selection of components from screen and processes them to create Scenes. My frustration is the Scenes are added in I assume creation order. I would like to simply take the selection list and sort it by Component Definition Name before passing the list to my Scene creation process. I have tried to find a snippet for sorting without success. Any pointers for Sorting in SU?

This is more a question for basic Ruby. You can attach a code block to the sort method of an enumerable to tell it how to compare elements for sorting. I’m on my phone now, so can’t give you an example.

1 Like
def sort_by_def_name(entites = Sketchup.active_model.selection)
  ents = entites.select{ |ent| ent.respond_to?(:definition) }
  ents.sort_by{ |ent| ent.definition.name }
end
2 Likes

Yeah, sort_by is the right way. For just sort you have to write a two argument comparison operator equivalent to <=>. Not complicated, just a bit different.

Edit: also be aware that the built-in String comparison is case-sensitive. Names that begin with a capital letter (e.g. auto-generated Group#1 and Component#2) will sort before lower case names.

1 Like
def sort_by_def_name(entites = Sketchup.active_model.selection)
  ents = entites.select{|ent| ent.respond_to?(:definition)}
  ents.sort{ |a, b| a.definition.name <=> b.definition.name }
end
1 Like

@dezmo @slbaumgartner Thank you both for your contribution. This will be a big help. I have a first stage mod working. :blush:

I’m not really much the wiser on the sort syntax, is that taken from basic ruby or is it in the SU extensions?

https://ruby-doc.org/3.2.2/Enumerable.html#method-i-sort

1 Like

Answer: This is from core Ruby.

In the SketchUp API documentation, pay attention to the box labeled Includes at the top of each API class. You will begin to notice that most all of the API collection classes have mixed in the Ruby core Enumerable module. This library module adds methods to any class that has mixed it in using include.

There are also some API classes that mix in the Comparable library module.

Also, when library modules are mixed in (using include, extend or prepend,) the library module acts as a pseudo-superclass and is inserted into the mixee’s ancestor chain.

Thanks for the explanation Dan. Although I have done simple programming in a variety of languages BASIC, LISP, GDL & some early machine code in Z80 chip days, it feels like I am on a steep learning curve with Ruby in the way it constructs lines of code and the interaction with SU. If I can see a way to improve my productivity I will spend some time working it out, but that is usually only achieved by a lot of trial and error. The pointers on this forum are very much appreciated.