Beginner Ruby Scripting

Chris Fullmer from SketchUcation and
Rick Wilson from Smustard

Web Console is a handy plug-in for Ruby Scripting on the PC.  It allows you to type in a number of lines and then press “go” to execute all the lines at once.  Whereas the SketchUp Ruby Console only has one line of input and each line is executed as it is typed in.

Request: Make the Ruby Console in SketchUp work like the plug-in.

How to Learn
  • Ruby tutorials (not relating to SketchUp, but just showing Ruby syntax)
  • SketchUp
  • How they interact, ruby and sketchup
  • SketchUp ruby methods are described in
  • Can also read blog, user comments in existing scripts
  • is a great resource
Run SketchUp
Go to menu Window > Ruby Console
type in commands

Example:  Get lists of entities in model
model = sketchup.active_model
e = model.entities
ae = model.active_entities
se = model.selected_entities

More complex example:
get the list of entities in the model
model = sketchup.active_model
ents = model.entities
note ents[0] will give you first entity
iterate through each entity and print to the console
iterate ents.each { |ent| puts ent}
filter the entities to just look at faces
ents.each {|ent| puts ent if ent.typename == “Face”}

Example of writing a ruby file
Q: should namespaces be important in ruby scripts
A: Yes, otherwise variables in one script could mess up variables in another script if they use the same names.

Write the following file called Greeble.rb that push/pulls selected faces at random heights
class Greeble
 def initalize(height=12)
   @heightrange = height

 def do_it(faces)
   faces.each do |face|

Save this file in the SketchUp plug-ins area: Library/Application Support/<more stuff>/plugins
Draw several faces in SketchUp and select just the faces, not the edges.
In ruby console type:
load “greeble.rb”
g =
g = greeble(50)
selection = model.selection

You should see the faces push/pull at random heights.
Notice if you undo, each push/pull on a single face is undone separately.  If you want to have them all viewed as a single operation and all undo/redo at once put them in an operation.
So edit greeble.rb and change the do_it as follows:

 def do_it(faces)
   faces.each do |face|

If you want to be able to select more than just faces and filter out the face from the selection change similarly to what we did earlier with ents:
faces.each {|face| face.pushpull(rand(@heightrange)) face if face.typename == “Face”}