Monday, November 7, 2011

Exercise 10: What Was That? Learn Ruby the Hard Way: Practicum


So in the last exercise, Zed showed us some new ways to get strings to appear
across multiple lines.  The first used a backslash and a characters 'n' together ('\n') to put a new line character into the string.

This is called an "escape sequence", and there are a number of ways to use them. The "back-slash" can also be used to print literal characters that otherwise would be used for command and syntax purposes, such as allowing us to print literal characters like ", ', or \ (we use \", \'. or \\ to show them in strings.

Here's an example Zed provides:

"I am 6'2\" tall."  # escape double-quote inside string
'I am 6\'2" tall.'  # escape single-quote inside string


I commented yesterday that there is a technique I've seen in Perl and used in CGI scripts (yes, I'm old enough to have written CGI :) ). Zed points out that this is referred to as "here" document syntax. Note: this displays weird in different browsers, so where you see the back slash, in this case, it's there so that I can print out what should be there, which is the two "less than" characters without the back slashes (see in the code snippets in the images if this is too confusing).

So let's check this out:

tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."


fat_cat = \<\
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
MY_HEREDOC


puts tabby_cat
puts persian_cat
puts backslash_cat
puts fat_cat


[and here's my attempt, with some annotation as to what's going on]






What You Should See


Look for the tab characters that you made. In this exercise the spacing is important to get right.


$ ruby ex10.rb
    I'm tabbed in.
I'm split
on a line.
I'm \ a \ cat.
I'll do a list:
    * Cat food
    * Fishies
    * Catnip
    * Grass


$


[and I do see it :)]




Extra Credit


Search online to see what other escape sequences are available.


[ Below are some of the more common escape sequences that can appear inside of double quotes.
\" – double quote
\\ – single backslash
\a – bell/alert
\b – backspace
\r – carriage return
\n – newline
\s – space
\t – tab


There are certainly more
]


Combine escape sequences and format strings to create a more complex format.


[see below]





TESTHEAD's TAKEAWAYS


So this is pretty cool. There's a number of tools we can use to allow us to get text to appear in ways that are not just starting at the beginning of the line, or even inserting noises (if you are into that sort of thing ;) ). I now have a proper name (here document) for the \<\

Sunday, November 6, 2011

Exercise 7, 8, 9: Lots More Printing: Learn Ruby The Hard Way: Practicum


So these are meant to be "chops building" exercises, and mostly just dealing with print statements, so there's not a lot of excitement going on here. I decided to group these three together since they are effectively the same thing, but I'm doing them :).













Exercise 7

So this is demonstrating the difference between using puts and print.

puts "Mary had a little lamb."
puts "Its fleece was white as %s." % 'snow'
puts "And everywhere that Mary went."
puts "." * 10  # what'd that do?

end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"

# notice how we are using print instead of puts here. change it to puts
# and see what happens.
print end1 + end2 + end3 + end4 + end5 + end6
print end7 + end8 + end9 + end10 + end11 + end12

# this just is polite use of the terminal, try removing it
puts

[and here we go]


What You Should See

$ ruby ex7.rb
Mary had a little lamb.
Its fleece was white as snow.
And everywhere that Mary went.
..........
CheeseBurger
$

[and that is indeed what I do see]

Extra Credit

For these next few exercises, you will have the exact same extra credit.

Go back through and write a comment on what each line does.

[see below]


Read each one backwards or out loud to find your errors.

From now on, when you make mistakes write down on a piece of paper what kind of mistake you made.

[just some typos and missing quotations with letters]

When you go to the next exercise, look at the last mistakes you made and try not to make them in this new one.


Exercise 8: Printing, Printing

So here's another printing example, to help us get more in the mood for formatting text. this shows us how we can declare a set of strings and print them following a single variable. Interesting.

formatter = "%s %s %s %s"

puts formatter % [1, 2, 3, 4]
puts formatter % ["one", "two", "three", "four"]
puts formatter % [true, false, false, true]
puts formatter % [formatter, formatter, formatter, formatter]
puts formatter % [
    "I had this thing.",
    "That you could type up right.",
    "But it didn't sing.",
    "So I said goodnight."
]

[and here we go]


What You Should See
$ ruby ex8.rb
1 2 3 4
one two three four
true false false true
%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s
I had this thing. That you could type up right. But it didn't sing. So I said goodnight.
$

[and yes, we see this]


Extra Credit

Do your checks of your work, write down your mistakes, try not to make them on the next exercise.


Exercise 9: Printing, Printing, Printing

And this is the last of the printing examples, and we do something unique with this one (actually, this reminds me of the <

# Here's some new strange stuff, remember type it exactly.

days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"

puts "Here are the days: ", days
puts "Here are the months: ", months

puts << p=""><>
There's something going on here.
With the PARAGRAPH thing
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
PARAGRAPH

[and one more time]


What You Should See

$ ruby ex9.rb
Here are the days:
Mon Tue Wed Thu Fri Sat Sun
Here are the months:
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
There's something going on here.
With the PARAGRAPH thing
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.

[and indeed I do :)]


Extra Credit

Do your checks of your work, write down your mistakes, try not to make them on the next exercise.

TESTHEAD's TAKEAWAYS


So the cool thing is that there are lots of things we can do to print out text and format the text, ranging from individual variables, multiple variables and even using the \<\< notation to create full blocks of text. Nothing earth shattering, but then doing reps in the gym isn't Earth-shattering either. It does become noticeable later on, though :).

Saturday, November 5, 2011

Exercise 6: Strings And Text: Learn Ruby The Hard Way: Practicum


Well, first thing, Zed just updated the site, and some of the changes make it easier to navigate through to the other pages and some of the changes help to hi-light code sections and make the distinctions cleaner. So props to what looks to be a nice redesign :).

OK, so today we are going to be taking a look at "string interpolation" and some more techniques that you can use to make strings behave the way you want to and take advantage of some unique properties in Ruby. You can tell you are looking at a string when you see text in 'single' or "double" quotes.

We can use string formatters (that was the '%' character and the designator that follows, see yesterday's table for the list I found), but that has some overhead, including the fact that, if you want to do more than one entry, you need to use the bracket characters at the end of the line and separate the values by commas. Workable, yes, but less readable, too.


There is another way to put variables directly into a string, using that fancy term I mentioned before; string interpolation. That really just means "hey, when you see these characters together, it means take the variable value and replace it inside the string. The format for doing that is to use the "octothorpe" character (remember that from earlier in the week?) immediately followed by a left curly brace, the variable name, and then a closing curly brace. Like this: #{variable_name}. So the answer to the question from comments: When is a comment character not a comment character? when it's paired with two curly braces. then it performs string interpolation. Woot!

In action:

The way we saw yesterday:

name1 = "Joe"
name2 = "Mary"
puts "Hello %s, where is %s?" % [name1, name2]

The String Interpolation way:

name1 = "Joe"
name2 = "Mary"
puts "Hello #{name1}, where is #{name2}?"


Even if you don't quite get what's going on, the second example is easier to read, even from a non coders perspective.

So our first exercise is as follows. Zed wants to have us write this out and tweak around with a bunch of variable substitiutions and print them to the screen. We also will be using shortened and abbreviated names. Remember when I said that longer, more descriptive names are helpful and make for readable code? I still stand by that, but for many, they like to make things short and tidy. Might as well get used to seeing it and working with it (but really) wnen possible, do with descriptive, it makes for code that self comments :) ).


x = "There are #{10} types of people."
binary = "binary"
do_not = "don't"
y = "Those who know #{binary} and those who #{do_not}."

puts x
puts y

puts "I said: #{x}."
puts "I also said: '#{y}'."

hilarious = false
joke_evaluation = "Isn't that joke so funny?! #{hilarious}"

puts joke_evaluation

w = "This is the left side of..."
e = "a string with a right side."

puts w + e

[and here is what we have]


What You Should See

There are 10 types of people.
Those who know binary and those who don't.
I said: There are 10 types of people..
I also said: 'Those who know binary and those who don't.'.
Isn't that joke so funny?! false
This is the left side of...a string with a right side.

[and that is indeed what I see]


Extra Credit

Go through this program and write a comment above each line explaining it.

[I think i got this right :)]



Find all the places where a string is put inside a string. There are four places.

[There are four places with literal "string" insertion (binary, do_not, x & y), but wait, there's more ;) ]

Are you sure there's only four places? How do you know? Maybe I like lying.

[Since the (10) and the false are not in quotes, they are not literally strings in the defined sense, but since they are entered into the #{} directly with the case of 10 and false is passed for variable interpolation via #{hilarious}, it is treated like a string]

Explain why adding the two strings w and e with + makes a longer string.

[This is called concatenation, and it basically says take the first part and add it to the second part. Since it's not mathematical or adding numbers, it interprets it as "take the first string and add the second string to it, not mathematically but put them side by side. If you have a better explanation, please comment :) ].


TESTHEAD's TAKEAWAYS

So that's pretty cool. Any character value that we put between #{} will be presented and interpreted as a literal string. this makes sense as there are many Cucumber Web Steps that do exactly this, so it's nice to see the official definition of how/why it is done this way. Also, interpolation can be encapsulated, meaning if you perform string interpolation to one variable, assign it to another, and do string interpolation a second time with the newly assigned variable, the original interpretation gets carried over.

Friday, November 4, 2011

Don't You Just Love "Good Intentions"?

Time for another bit of levity from Aaron Scott and Two Leaf Clover :).

I've said before that I like it best when Aaron gets ironic. This is a gem. Sure, you are laughing at the total inappropriate placing of a fire extinguisher in the desert, but what makes it even more funny (and painful) is how many places in our everyday life we come across well intentioned but completely useless contingency plans.


Seriously, think about all of the things that are in place to "keep people safe" or to "make sure something bad doesn't happen". Believe me, I'm a tester, I'm intimately familiar with the fact that people will figure out how to do bad, inappropriate, or messed up things. It's something in our DNA, I'm convinced of it.


A favorite quote of mine is attributed to Jerry Weinberg, and that is "Quality means value to some person, at some time, who matters." Sometimes the most asinine (my words) restrictions on doing something, or placement of items of dubious value, are often there because someone with influence and importance decided it was important. They may have the best of intentions, but somehow they are unable to see that their idea, their issue, their challenge, may be of very little importance to someone else. I had a chuckle a couple of days ago as I saw an ATM machine, freestanding, outside of a South of Market bar, that had effectively been vandalized, ripped open and left as a reminder that good intentions and good ideas also need to be in good places... perhaps, I don't know... inside the bar?!


Still, it's fun to look around and see various interesting and curious placement of items that just make you scratch your head and ask "what were these people thinking?" Most of the time, it comes back to the same place and thought. It mattered to them at the time, and in that "at the time" state, what they were doing made perfect sense. It's only in hindsight and after we see what follows on that we get a clear view of a situation, and can actually understand that the road to hell and to numerous failures is paved with "good intentions". The difference between a road to hell and a road to failure is that we have a chance to learn from the failures. If we do learn from them, then we haven't really failed, we just figured out another way that something will not work on our way to something that will.


So here's a suggestion; today, take a look at something you are working on, and try to discover what your good intention is. Just don't stop there. Try to figure out what you are actually doing with it, and if it will indeed be a real benefit, or "another fire extinguisher in the desert".

Exercise 5: More Variables And Printing: Learn Ruby The Hard Way: Practicum

Up to now we have just been typing "puts" and then following on with some text in quotes, or variable names not in quotes. The values of the variables get printed to the screen. The text between the quotes is referred to as a "string". Yeah, I know, this is really basic stuff so far, and that's fine. The intermediate hill is coming up soon, though so there is some value to paying attention in these earlier phases :).

This particular exercise shows how to do more than just print a set of characters between double quotes. Variables can also be inserted into the text strings so that the lines printed out aren't just static text.

So here's the first exercise:

As usual, just type this in even if you do not understand it and make it exactly the same.

1 my_name = 'Zed A. Shaw'
2 my_age = 35 # not a lie
3 my_height = 74 # inches
4 my_weight = 180 # lbs
5 my_eyes = 'Blue'
6 my_teeth = 'White'
7 my_hair = 'Brown'
8
9 puts "Let's talk about %s." % my_name
10 puts "He's %d inches tall." % my_height
11 puts "He's %d pounds heavy." % my_weight
12 puts "Actually that's not too heavy."
13 puts "He's got %s eyes and %s hair." % [my_eyes, my_hair]
14 puts "His teeth are usually %s depending on the coffee." % my_teeth
15
16 # this line is tricky, try to get it exactly right
17 puts "If I add %d, %d, and %d I get %d." % [
18 my_age, my_height, my_weight, my_age + my_height + my_weight]

[…and here we go]



What You Should See

$ ruby ex5.rb
Let's talk about Zed A. Shaw.
He's 74 inches tall.
He's 180 pounds heavy.
Actually that's not too heavy.
He's got Blue eyes and Brown hair.
His teeth are usually White depending on the coffee.
If I add 35, 74, and 180 I get 289.
$


[yep :) ]


Extra Credit

Change all the variables so there isn't the my_ in front. Make sure you change the name everywhere, not just where you used = to set them.


[Done, Zed's point being, the variables once defined will look for those values specifically. If the 'my_' isn't deleted everywhere, you will have a variable with no assignment or definition, and you will get an error. Fun, huh :)?]

Try more format sequences.

[I added a couple to the code and made some separate puts statements to specify what they are]



Search online for all the Ruby format sequences.

[
Found these at ruby-doc.org. Not sure if it's all of them, but it's a pretty good list:


b - Convert argument as a binary number.
c - Argument is the numeric code for a single character.
d - Convert argument as a decimal number.
E - Equivalent to `e', but uses an uppercase E to indicate the exponent.
e - Convert floating point argument into exponential notation with one digit before the decimal point. The precision determines the number of fractional digits (defaulting to six).
f - Convert floating point argument as [-]ddd.ddd, where the precision determines the number of digits after the decimal point.
G - Equivalent to `g', but use an uppercase `E' in exponent form.
g - Convert a floating point number using exponential form if the exponent is less than -4 or greater than or equal to the precision, or in d.dddd form otherwise.
i - Identical to `d'.
o - Convert argument as an octal number.
s - Argument is a string to be substituted. If the format sequence contains a precision, at most that many characters will be copied.
u - Treat argument as an unsigned decimal number.
X - Convert argument as a hexadecimal number using uppercase letters.
x - Convert argument as a hexadecimal number.
]

Try to write some variables that convert the inches and pounds to centimeters and kilos. Do not just type in the measurements. Work out the math in Ruby.

[See below. I used the % [height * 2.54] evaluation to convert height in inches into a temporary conversion value. Note that height has not actually been given a new value. Also, % [weight / 2.2] did the same thing; it made a temporary conversion value of weight and represents it in kilograms (with 2 points of decimal precision). Weight is still the same value, if we called weight by itself, it would also appear with its original value. This is a good way to do some temporary conversions and not have to litter the code with a bunch of variable declarations. If you wanted to store that intermediate value to be used somewhere else later on in the program, then yes, it would make sense to actually create another variable and then use it there (such as "kilo_weight = weight / 2.2"].


TESTHEAD's TAKEAWAYS:

OK, so there are a couple of cool things to consider here. The first is that Zed is already starting to show that we need not be spoon fed in everything. He didn't give us the character strings to use, he had us go look for them, a valuable skill in our "LMGT" (Let Me Google That) for you world. If they are printed, we'll just scan them and use something. If we have to look for them, we have to actually think about what we are after and what they might be represented as. Searching for "string modifiers for Ruby" got me less than satisfactory results, but as I did some poking, I saw reference to "sprintf" and thought, OK, how about searching for "sprintf string modifiers"... and ta-daa, the table above is what I got in the first link :).

The second thing is that we can do a lot of things on the fly, especially if the value we need is only going to be used once. This lets us see what the operations are that are needed to create this temporary value that we display. If we're doing a lot of manipulations, we may want to keep that intermediate value and any others that appear in separate variables. However, a lot of formulas deal with known values and constants, so instead of storing everything independently, we can manipulate a lot of the values on the fly (this should be no big revelation to anyone that has ever worked with a shell script, but hey, I still think it's pretty cool to be able to do that).

Thursday, November 3, 2011

Weekend Testing Americas This Saturday

I have missed having Weekend Testing Events. It's been awhile since I've been able to participate in one. First it was due to my accident and then I was out of town for the AST Board Meeting. But now I'm mostly healed, mostly ambling, an it's time to get back in the saddle. Only this time, I will be riding shotgun.

It's with great pleasure that I am able to hand over the active reins for some of these sessions to Albert Gareev, another dedicated tester who has gamely stepped up to assist an facilitate Weekend Testing sessions. For the past year, the sessions that happened did so because of my schedule, so the hit and miss nature of them was entirely due to when I was around. Albert has been an active contributor and has gamely learned the ropes so that he could be another active facilitator as well. this makes it possible for us to offer a more flexible schedule.

One of the benefits of being a facilitator is that, since you are the one running the show, you get to run the show at a time that is convenient for you to do so. Others come along for the ride if they want to, or don't. When I do sessions, it's typically at 11:00 AM Pacific Time, and then everyone else around the world adjusts their schedules so they can participate (I feel somewhat sorry for the testers in India when they participate in our sessions; that means they are online at 12:30 PM their time). Since Albert's the facilitator, he gets to choose the time he wants to present, so he has chosen 12:00 PM Eastern, which translates to 9:00 AM Pacific this coming Saturday, November 5th, 2012.

This weekend's session is meant to be a group training session, and Albert has asked that we come prepared with Mozilla Firefox installed and also to install the GroundSpeed Add-on. What will we be doing? Well that's typically kept close to the vest by the facilitator so as to not tip their hand or give too many people the chance to "study up". One of the biggest general benefits of Weekend Testing is that most testers come in with the same information at the start of the session, meaning they may know the general idea of what they will be testing, but they don't know the specifics. When we announce the specifics, everyone then starts from the same point and can help inform each other. Veterans can help newcomers, and sometimes newcomers have an edge on veterans depending on the mission and charter. All this is a fancy way of saying "I don't know what Albert has planed, but I expect it will be cool, and I'll expect you might want to come check it out" :).

So how can you do that? It's simple.

1. Add “WeekendTestersAmericas” to your Skype contacts if you haven’t already.


2. Fifteen minutes prior to the start of the session this coming Saturday, message “WeekendTestersAmericas” and ask to be added to the chat session. Once we see you, we will add you to the session.

You can also send an email message to WTAmericas@gmail.com and ask to be aded to our mailing list, so that you can be one o the first to receive an announcement for upcoming testing sessions.

We hope to see you there :).

Exercise 4: Variables And Names: Learn Ruby The Hard Way: Practicum


So as most people are already aware, variables are pretty important when it comes to any level of programming. It's what makes your programs actually flexible and able to do more than just the most static of things. All that a variable does is make a placeholder and a name for something. A variable can be named, well, anything, but seriously, you will do both yourself and everyone else who interacts with your code a big favor if you actually make your variables names be things that people will understand. If you want to make an equation that includes the speed of light as a variable, "speed_Of_Light" is a much more useful variable than "l". It also makes your code a lot more readable.

Variables are also one of the areas where, if you are typing in stuff by hand in a generic text editor, they are both a blessing and a curse. A blessing in that typing gets easier, a curse in that you need to make sure you are as consistent as you think you are.

So here's the exercises...

Write a comment above each line explaining to yourself what it does in English.
Read your .rb file backwards.
Read your .rb file out loud saying even the characters.
 1 cars = 100
 2 space_in_a_car = 4.0
 3 drivers = 30
 4 passengers = 90
 5 cars_not_driven = cars - drivers
 6 cars_driven = drivers
 7 carpool_capacity = cars_driven * space_in_a_car
 8 average_passengers_per_car = passengers / cars_driven
 9
10 puts "There are #{cars} cars available."
11 puts "There are only #{drivers} drivers available."
12 puts "There will be #{cars_not_driven} empty cars today."
13 puts "We can transport #{carpool_capacity} people today."
14 puts "We have #{passengers} passengers to carpool today."
15 puts "We need to put about #{average_passengers_per_car} in each car."

Note: The _ in space_in_a_car is called an underscore character. Find out how to type it if you do not already know. We use this character a lot to put an imaginary space between words in variable names.

What You Should See

$ ruby ex4.rb
There are 100 cars available.
There are only 30 drivers available.
There will be 70 empty cars today.
We can transport 120.0 people today.
We have 90 passengers to carpool today.
We need to put about 3 in each car.
$

[Yep :)]

Extra Credit

When I wrote this program the first time I had a mistake, and Ruby told me about it like this:

ex4.rb:8:in `
': undefined local variable or method `car_pool_capacity' for main:Object (NameError)

Explain this error in your own words. Make sure you use line numbers and explain why.

[When Zed originally wrote the line for line 7, he added an extra underscore. This referenced a variable that doesn't exist. Line 8 is where the error is recognized, so the Ruby interpreter says there's an error at line 8.]

Here's more extra credit:

Explain why the 4.0 is used instead of just 4.

[By using 4.0, we put the calculations into floating point numbers, and that allows us to deal with fractional values. Otherwise everything would be calculated using only integer values. Also shows that you only need one floating point value for all the equations that involve it to be treated as floating point numbers]

Remember that 4.0 is a "floating point" number. Find out what that means.

[see above]

Write comments above each of the variable assignments.
[see above]

Make sure you know what = is called (equals) and that it's making names for things.
[Actually, the equals sign in this case is an assignment operation, as in "cars is assigned the value of 100"]


Try running IRB as a calculator like you did before and use variable names to do your calculations. Popular variable names are also i, x, and j.

TESTHEAD TAKEAWAYS:


We will be doing ourselves a huge favor if we create variable names and assignments that we can actually read. This is the idea behind self documenting code. It made sense in the days of finite limited RAM to be stingy with code naming because executables when compiled needed to fit in their specific locations and not over run memory (and in embedded devices, this is still true). Having said that, making your code "self documenting" can go a long way towards making the code you write more understandable to those reading and maintaining code. One of the best ways to make code self documenting? Use consistent and well spelled out variables.

Wednesday, November 2, 2011

A TESTHEAD ST&QA Double Play :)

     In the October 2011 (Vol. 8 No. 5) version of ST&QA Magazine, I get to have a double play :).

     First, this issue is dedicated to the release of our book "How to Reduce The Cost of Software Testing" (available from both the Publisher, Taylor & Francis and from Amazon) and there are a number of stories that are focused on the topic. Many of them are all new material that was written after the book had wrapped. The cover story, coolly enough, is an excerpt of my chapter (Trading Money for Time: When Saving Money Doesn't (and When It Does).


Second, and really humbling is a piece called "What is the Cost of Testing?" in which Rich Hand interviews, well... me! We had a great conversation a while  back, and only about 50% of it appears in the article. Rather than structuring it like an interview, it's a narrative with many of my thoughts interjected. Maybe this is a better approach; Rich was able to edit out areas where I probably rambled a bit (LOL!). Still, I think it's an accurate and representative piece, and I'm happy to have had a chance to be a part of it.

So for those interested in getting a copy ST&QA, go to the SoftwareTestPro.com site and download it, or you can read both the Cover Story or my Interview right there on the site. If you do, please leave a comment or two, I'd love to know what you think :).

Exercise 3: Numbers And Math: Learn Ruby The Hard Way: Practicum


Performing calculations is an important part of any programming language, and Ruby is no exception. Many people have been led to believe that to be a computer expert you have to be a mathematics expert (and Computer Science and Engineering requirements certainly don't dispel that rumor; it's a lot of the reason why I have an I.S. degree rather than a C.S. or E.E. degree ;) ). Still in many instances, the math that is performed is actually pretty straightforward. Most of the math symbols will be perfectly familiar to anyone who has done any kind of programming in the past or even worked with Excel.

For the first exercise, Zed has us saying out loud what everything is. It helps to know what these things are so when you mention a "modulus" character to another programmer, or them to you, you know what it is :).

And here we go...

+ plus [performs addition]
- minus [performs subtraction]
/ slash [performs division]
* asterisk [performs multiplication]
% percent  [provides the remainder of a division, i.e. the modulus]
&lt; less-than [what's on the left is less than what's on the right]
> greater-than [what's on the left is greater that than what's on the right]
&lt;= less-than-equal [what's on the left is less than or equal to what's on the right]
>= greater-than-equal [what's on the left is greater than or equal to what's on the right]

The first thing to do was to tell what the operations were, fairly straightforward [see above]

Next, let's get gedit and ruby in to the game:


 1 puts "I will now count my chickens:"
 2
 3 puts "Hens", 25 + 30 / 6
 4 puts "Roosters", 100 - 25 * 3 % 4
 5
 6 puts "Now I will count the eggs:"
 7
 8 puts 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
 9
10 puts "Is it true that 3 + 2 &lt; 5 - 7?"
11
12 puts 3 + 2 &lt; 5 - 7
13
14 puts "What is 3 + 2?", 3 + 2
15 puts "What is 5 - 7?", 5 - 7
16
17 puts "Oh, that's why it's false."
18
19 puts "How about some more."
20
21 puts "Is it greater?", 5 > -2
22 puts "Is it greater or equal?", 5 >= -2
23 puts "Is it less or equal?", 5 &lt;= -2

[see below]


What You Should See

$ ruby ex3.rb
I will now count my chickens:
Hens
30
Roosters
97
Now I will count the eggs:
7
Is it true that 3 + 2 &lt; 5 - 7?
false
What is 3 + 2?
5
What is 5 - 7?
-2
Oh, that's why it's false.
How about some more.
Is it greater?
true
Is it greater or equal?
true
Is it less or equal?
false
$

[yep, that is indeed what I am seeing]

Extra Credit

Above each line, use the # to write a comment to yourself explaining what the line does.
[see below]



Remember in Exercise 0 when you started IRB? Start IRB this way again and using the above characters and what you know, use Ruby as a calculator.

[see below]


Find something you need to calculate and write a new .rb file that does it.
[see below]



Notice the math seems "wrong"? There are no fractions, only whole numbers. Find out why by researching what a "floating point" number is.
Rewrite ex3.rb to use floating point numbers so it's more accurate (hint: 20.0 is floating point).

[see below]



TESTHEAD's TAKEAWAYS

It can be tricky to know what gets worked on first with a string of characters and no designation. For me personally, I like to use parentheses even if the system is smart enough to figure them out (the system might be, but I want to know it's doing what I want it to, so I use the parentheses to keep it straight). Even if we don't use parentheses, the system will use mathematical order of operations to evaluate values, so make sure you are writing them out the way that you intend to... or again, use parentheses if you want to make sure you are calculating the values you think you should be calculating.

Tuesday, November 1, 2011

Exercise 2: Comments And Pound Characters: Learn Ruby The Hard Way


So the last exercise had us typing in characters to help us understand what lines would be printed to the screen and which ones wouldn't. The character used is the 'octothorpe', aka 'pound', 'hash', 'number key', hey, whatever works for you. The important thing is that wherever it appears, any character that follows on after it doesn't get run in the program. It's used for commenting your code and for disabling lines in your code.


So here's the exeercises as dispayed in the book and what I see when I run them.



1 # A comment, this is so you can read your program later.
2 # Anything after the # is ignored by Ruby.
3
4 puts "I could have code like this." # and the comment after is ignored
5
6 # You can also use a comment to "disable" or comment out a piece of code:
7 # print "This won't run."
8
9 puts "This will run."




[And here it is]



What You Should See



$ ruby ex2.rb

I could have code like this.

This will run.

$








[so far so good]



Extra Credit



- Find out if you were right about what the # character does and make sure you know what it's called (octothorpe or pound character).



[Well, yeah, the pound character, when it is by itself and with a space next to it, acts as a "comment" character. Here's the thing, it doesn't always do that. there are examples where when combined with other characters it means something else, but that's jumping ahead in the exercises]



- Take your ex2.rb file and review each line going backwards. Start at the last line, and check each word in reverse against what you should have typed.



[done, looks clean under the circumstances]



- Did you find more mistakes? Fix them.



[this time, no, I think we are clean]



- Read what you typed above out loud, including saying each character by its name. Did you find more mistakes? Fix them.



[I had some spacing issues and cleaned them up, but otherwise, looks clean from what I can see]



TESTHEAD's TAKEAWAYS



OK, seriously, did Zed really make me just do that? Does he think I'm really that stupid? Well, no... and yes. You see, in reality, we are that stupid, if we are inexperienced or we are not really good typists. We think we have typed our information well. We think we have done everything right, until we actually run the program and it gives us output that we don't expect, or we get an error. By reading the code backwards, we can see if, indeed, we did write what we believe we wrote. Remember, the human brain can make sense out of a lot of static, and it's very helpful when it comes to filling in the blanks and letting us see what we think we mean.


I see this all the time with my own blog posts. I proofread them, sometimes two or three times, only to have another reader spot a glaringly obvious error that I overlooked. Why? Because my brain knows what I mean, and it is more than happy to fill in the blanks. Computers can't do that; they have to be told explicitly what to do, and even elegant layers of abstraction, of which Ruby is, cannot overcome that. If you tell the computer to do something, it will do it, whether you meant to tell it that or not. It doesn't understand intent. So yeah, Zed wants you to proofread even these simple starter programs. You may be surprised how many flaky things you do and do not realize at all that you are doing them.