Blog

Exercise 19: Functions And Variables: Learn Ruby The Hard Way: Practicum (TESTHEAD)

On November 16, 2011, in Syndicated, by Association for Software Testing
0

So, yeah, how did that last chapter feel? A bit heavy? I’ve found it best to sort of think of functions like my old guitar pedals. The sound from your guitar goes in, the pedal does some fun stuff, and what comes out and heads to your amp is juiced and interesting (I’m adding that for Zed’s benefit, since I know he’s a guitar player 😉 ).

Each function works its own set of magic on what comes in, and makes for a unique different thing that comes out (i.e. what goes on inside of the functions themselves have no bearing on what other functions do. A good thing to keep in mind).

Speaking of keeping that in mind, here’s an example of how what I just said up above works.

The key point here is that we can pass just about anything to our script as parameters. Straight numbers. variables, math values, variables and math values combined. The idea is, if we can assign it to a variable, we can probably pass it as a parameter to a function.

What You Should See

$ ruby ex19.rb
We can just give the function numbers directly:
You have 20 cheeses!
You have 30 boxes of crackers!
Man that’s enough for a party!
Get a blanket.

OR, we can use variables from our script:
You have 10 cheeses!
You have 50 boxes of crackers!
Man that’s enough for a party!
Get a blanket.

We can even do math inside too:
You have 30 cheeses!
You have 11 boxes of crackers!
Man that’s enough for a party!
Get a blanket.

And we can combine the two, variables and math:
You have 110 cheeses!
You have 1050 boxes of crackers!
Man that’s enough for a party!
Get a blanket.
$

Extra Credit:

– Go back through the script and type a comment above each line explaining in English what it does.

– Start at the bottom and read each line backwards, saying all the important characters.

[I’ll leave that to the reader, but suffice it to say that the comments and this exercise will help you see why what goes where (say that ten times fast 😉 ]

– Write at least one more function of your own design, and run it 10 different ways.

TESTHEAD’s Takeaways:

Functions can take lots of values as the parameters, the point that anything that can be assigned as a variable can be entered as a parameter looks to hold true. we can do lots of math operations if we want to as well, and we can even do type conversion (I looked up how to convert integers to floating point numbers so that we could get realistic numbers for percentages, and yes, we have a rounding error since I limited it to 2 significant digits, but you get the point 🙂 ).

 

Comments are closed.


Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!