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.

<strong>Architectural</strong> <strong>Design</strong> <strong>with</strong> <strong>SketchUp</strong><br />

As in other programming languages, Ruby has a large set of useful functions to accomplish<br />

a whole lot of operations on arrays, such as sorting and reversing (see Appendix B for<br />

a handy reference).<br />

TIP<br />

In addition to “classic” arrays, Ruby can store key-value pairs of information in a special<br />

kind of array, a hash.<br />

grades = Hash[“Mike” => 88, “Lucie” => 99]<br />

Some String Peculiarities<br />

If you use single quotes (as in ‘Hello’) to define a string, the text will be output as is. If you<br />

use double quotes (as in “Hello”) to define a string, any inline variable (as in #{myvar}) or command<br />

(such as the newline command \n) <strong>with</strong>in the string will be interpreted. Also, if your text<br />

contains quotes themselves, you must escape them <strong>with</strong> a leading backward-slash \. Here is<br />

an example that illustrates this:<br />

author = ‘someone’<br />

puts ‘This is #{author}\’s text.\nWho wrote it?’<br />

will output This is #{author}’s text.\nWho wrote it?. If you use double quotes instead:<br />

author = ‘someone’<br />

puts “This is #{author}\’s text.\nWho wrote it?”<br />

this will be the result:<br />

This is someone’s text.<br />

Who wrote it?<br />

As you can see, the newline was interpreted as such, and the author variable was inserted<br />

into the string. Other useful escape strings are \t for inserting a tab and \\ for getting a<br />

single backslash.<br />

If you want to use a formatted string, use the format or sprintf function, as in:<br />

sprintf(“%s: %d”, “Value”, 123)<br />

This outputs Value: 123. As shown here, you can easily assign variables to placeholders<br />

this way. This is very useful if you want to write a formatted string to a file.<br />

Reusing Stuff: Declaring and Using Methods<br />

As always, the more you do <strong>with</strong> what you already have, the better. Therefore, if you reuse<br />

the same functionality more than once in your script, it makes sense to “package” it into a<br />

method. Ruby does this by simply using the def keyword:<br />

238<br />

def my_function( salutation, name )

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

Saved successfully!

Ooh no, something went wrong!