19.12.2016 Views

Architectural_Design_with_SketchUp

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 6 Creating Geometry Using Ruby Scripting<br />

puts “Hello, #{salutation} #{name}”<br />

return name.length<br />

end<br />

len = my_function( “Mr.”, “Bond” )<br />

puts “Your name is #{len} characters long”<br />

As you can see, you can assign attributes (such as name) to a method, let it do things,<br />

and even return values.<br />

With Ruby being an object-oriented language, the most elegant (and language-appropriate)<br />

way to reuse code is to write a class that defines methods and variables and then use it by declaring<br />

a new object instance based on this class. Because the main focus of this chapter is to create<br />

geometry and to get you started in Ruby, the discussion of classes is intentionally omitted here.<br />

Controlling Things: IF/THEN/ELSE<br />

You may want to do something in your code after checking something else. You can do this<br />

easily <strong>with</strong> the following lines:<br />

length = 10<br />

if length < 10<br />

puts “Short”<br />

elsif length > 10<br />

puts “Long”<br />

else<br />

puts “Exactly 10”<br />

end<br />

Modify this snippet to your needs. For example, you don’t need the elsif or else parts<br />

if all you are checking for is length < 10. Also, the complete list of comparative operators<br />

is , ==, =, and != for “not equal.” You can combine comparisons using && for<br />

“and” and || for “or” as in length == 10 && color == ‘blue’.<br />

There are other ways to use the if statement, too. Here are some examples:<br />

# used as a statement modifier<br />

puts ‘Exactly 10’ if length == 10<br />

# used as a one-liner<br />

if length == 10: puts ‘Exactly 10’ end<br />

# the ‘ternary operator’ version for assignment<br />

label = length == 10 ? ‘Exactly 10’: ‘Not 10’<br />

You can always use the exclamation mark to negate a comparison, as in !(length == 10).<br />

TIP<br />

239

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!