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 />

Storing Stuff: Variables and Constants<br />

As demonstrated, you can simply assign anything to a variable name of your choosing (e.g.,<br />

a = 1.2). This works <strong>with</strong> a string, a float number, an integer, an array, or an object. You<br />

don’t have to even declare the variable’s type as you often need to do in other programming<br />

languages.<br />

When using variables, start the name <strong>with</strong> a lowercase letter or an underscore (“_”).<br />

Uppercase first letters are reserved for methods and constants (e.g., for PI). You can assign<br />

constants, then, such as MYNAME = “Alex”.<br />

TIP<br />

You can even mix types, for example, in your calculations:<br />

a = 1.2<br />

b = 2<br />

a * b<br />

# a float number<br />

# an integer number<br />

This correctly gives you 2.4 as the result. Just keep in mind that numbers stored as strings<br />

don’t automatically convert in your calculations; use to_f (for float numbers) and to_i (for<br />

integers) first. If you had started the three lines of code <strong>with</strong> a = “1.2” (<strong>with</strong> the quotation<br />

marks, thereby defining this as a string), the calculation would not have worked. The last line<br />

would then have to be changed to a.to_f * b instead.<br />

A useful constant is __FILE__ (<strong>with</strong> two underscores on either side of the word FILE). It<br />

always gives you the current Ruby file’s name and location.<br />

TIP<br />

It is important to remember that these variables are local variables. This means that they<br />

work only wherever they were declared (<strong>with</strong>in a program or a function). If you need a variable<br />

to work globally, add a dollar sign to the front: $a.<br />

If you want to use a collection of items, it is often best to store them in an array. An array<br />

can, for example, contain a set of coordinates, names, or values. There are two ways to add<br />

elements to an array. Either do it when you create the array:<br />

names = [“Michael”,”John”,”Agnes”]<br />

or first create an empty array and then add elements (to the end):<br />

names = []<br />

names.push (“Michael”,”John”,”Agnes”)<br />

If you want to access an element of an array, write (in our example) names[1] to get<br />

“John”. Always remember that an array starts at index zero!<br />

237

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

Saved successfully!

Ooh no, something went wrong!