Learn Ruby the Hard Way Exercise 32: Loops and Arrays

Exercise 32 shows….Arrays.  Arrays are indexed lists of stuff that can be assigned to a variable.   So far as I know at this point they can contain basically any object- stirngs (and string interpolation), integers and floast, true or false values and hashes and others arrays.

Objects inside arrays are referenced using numbered indices

arr = Array.new
arr.push([“Cat”, “Pig”, “Duck”])

The items inside the array will be indexed and can be access this way (starting at 0)

puts arr[0]  #=> Cat
puts arr[1]  #=> Pig
puts arr[2]  #=> Duck

Here is the code for exercise 32:

ex32 code

On line 3-5 we created a bunch of different arrays that have Integers and stringes applied to them.

The looping part of the title of the exercise refers to creating code that goes through and does stuff to each item in an array. There are two different ways of doing this given above – on lines 7-9 we have a for loop, a more common way of doing this is in ruby is given on lines 12-14 using the .each method.  On Line 26 a similar loop is written using {} curly braces instead of do-end keywords. In Ruby the curly braces are generally interchangable with the do-end keywords.

Here is the output:

This is the count: 1
This is the count: 2
This is the count: 3
This is the count: 4
This is the count: 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricotes
I got 1
I got pennies
I got 2
I got dimes
I got 3
I got quaters
adding 0 to the list
adding 1 to the list
adding 2 to the list
adding 3 to the list
adding 4 to the list
adding 5 to the list
Element was: 0
Element was: 1
Element was: 2
Element was: 3
Element was: 4
Element was: 5
=> [0, 1, 2, 3, 4, 5]

Study Drills

1. Take a look at how you used (0..5) in the last for-loop.  Look up Ruby’s “range operator” (.. and …) online to see what it does.

A range object represents the values between the start and end value.  It saves memory as you can store a huge a amount of data without having to put each individual value in so for example if we wanted to represent the number 1-ten zillion we could write 0..10000000.

We can assign the results to a variable and use it to compare stuff.

years_range = 1980..2017
my_birthday = 1985

=> true

Behind the scenes this uses the .succ method that returns the next element in a data type range so

1.succ #=>2,

B.succ #=> C

This doesn’t work with floats(decimals.) Interestingly you can also use the .to_a method on arrays that contain ranges to fill them up. I suppose this is faster.

test=  (‘a’..’d’).to_a
print test

[“a”, “b”, “c”, “d”]=> nil

2. Change the first for number in the_count to be a more typical .each style loop like the others.

the_count= [1,2,3,4,5]

the_count.each {|x| puts “This is the count: #{x}”}

This is the count: 1
This is the count: 2
This is the count: 3
This is the count: 4
This is the count: 5
=> [1, 2, 3, 4, 5]


3. Find the Ruby documentation on arrays and read about them.  What other operations can you do beside the push function? Try <<, which is the same as push but is an oeprator. Fruits MM x is the same as fruits.push(x)

There are tons of array methods but here are some of the ones I found out about:

  • The .size and. length methods can return the number of elemenents in an array
  • An you can compare to arrays to remove duplicates thus:
  • .clear will empty an array of elements
  • .empty? will return true if an array is empty
  • .compact will removes all nil values from an array
  • .pop removes last elements, can be given ( ) parameters to specify how many elements to pop
  • .reverse – reverses the order of elements
  • .sort sorts lists of integers or strings, cannot compare the two or true/fals
  • .to_a to array method, we can use it like this

alphabet = (‘a’..’z’).to_a

#=> assigns all letters in alphabet to the the variable on the left.




Learn Ruby the Hard way Exercise 31: Making Decisions

This exercise expanded on the last and showed a simple fun text game that uses nests of if-statements within if-statements to create more branching output based on the users choices. What caught my eyes was the % symbol used on line 19. Here is can be used reference the users input (assuming none of the conditions for the if/elsif were met.)

Here is the code for exercise 31:


Exercise 31 code

The code above is basically two if-statements nested within the if and elsif keywords of a larger if-statement.

Study Drills

Make new parets of the game and change which decisions people can make. Expand the game out as much as you can before it gets ridiculous.

I didn’t do much apart from add a third elsif branch if the users picks a third door I added.  One of the options prints the entire lyrics for the song Safety Dance. No joke. But seriously you could add millions of elsif options to the top level if-statement and if your text editor allows you to collapse these branches it will still be kind of legible.

Write a completely new game. Maybe you don’t like this one. so make your own. This is your computer, do what you want!

Ok. I made this game based on this song. I made it quite lengthy before I got bored and moved onto the next exercise.

puts “””
You’re walking in the woods
There’s no one around and your phone is dead


puts “””Out of the corner of your eye, you spot him
(Shia LaBeouf)

He’s following you about thirty feet back
He gets down on all fours and breaks into a sprint
He’s gaining on you.
What do you do?

1.Get to the car!
2.Run for your life!


part1 == “1”
puts “Shia Labeouf catches you while your fumbling for your keys. Goood Job!”
part1 == “2”
puts “He’s almost upon you now, and you can see there’s blood on his face”
puts “My God, there’s blood everywhere!”
part2 = gets.chomp

puts “””
Now it’s dark and you seem to have lost him
You see a cabin in the woods

1. creep silently through the underbrush away from the cabin.
2. Move toward the cottage, quietly.”””

part2 = gets.chomp

part2 == “1”
puts “You move stealthily toward it
But your leg! AH! It’s caught in a bear trap!”

puts “> ”
puts “What do you do?
1. Saw off your leg
2. Try to pry the bear trap open”
part2_sub =gets.chomp
part2_sub == “1”
puts “You gnaw off your leg and limp towards the cottage”

elsif part2_sub == “2”
puts “You try to escape the bear trap but it’s too strong and Shia LaBeouf heard that and caught you. Good job!”
puts “You tried %s but Shia LaBeouf heard that and caught you. Good job!” %part2_sub

part2 == “2”
puts “Now you’re on the doorstep but sitting inside is Shia Labeouf
Sharpening an axe!”
puts “You tried %s but Shia LaBeouf heard that and caught you. Good job!” %part2

puts “> ”
puts “But wait he doesn’t here you:”
puts “What do you do? ”
puts “1. Sneak up and strangle him”
puts “2. Wrestle the axe from him”

part3 = gets.chomp
if part3 == “1”
puts “You strangle him. Your safe at last from Shia Labeouf”
elsif part3 == “2”
puts “Shia LaBeouf overpowers you. Good job!”
puts “You tried %s but Shia LaBeouf heard you and attacks you with his axe. Your dead….good job!” %part3
puts “You tried to %s but Shia Labeouf caught you. Good job!” %part1



Learn Ruby the Hard Way, Exercise 29: What if

This exercise introduced the if keyword which checks to see if a condition is true or false, if true the if keyword tells the program to execute the following code block.

Here is the code for exercise 29.

people = 20
cats = 30
dogs = 15

if people < cats
puts “Too many cats! the world is doomed!”

if people > cats
puts “Not many cats! The world is saved!”

if people < dogs
puts “The world is drooled on!”

if people > dogs
puts “The World is dry!”

dogs +=5

if people >=dogs
puts “People are greater than or equals to dogs”

if people <= dogs
puts “People are less than or equal to dogs.”

if people == dogs
puts “People are dogs”


Running this script returned:

Too many cats! the world is doomed!
The World is dry!
People are greater than or equals to dogs
People are less than or equal to dogs.
People are dogs
=> nil


Study Drills

In this study drill, try to guess what you think the if-statement is and what it does. Try to answer these questions in your own words before moving on to the next exercise:

1. What do you think the if does to the code under it?

If the condition is true we run it, if not we move onto the next block of code.

2.Why does the code under the if need to be indented two spaces?

It doesn’t but it does make the code more legible and I’m pretty sure its a Ruby convention.

3. What happens if it isn’t indented

Nothing will happen and the code will run the same

4. Can you put other Boolean expression from Exercise 27

Yes you can. You can make a whole entire complex medley with boolean expression if you wanted to.  I added ‘&& !(true && false)’ to the code below and it evaluated to true.

if people < cats  && !(true && false)
puts “Too many cats! the world is doomed!”

This basically says, if people are less than cats equals true and the other operand equals true (it does) then puts the string below.

5. What happens if you change the initial value for people, cats and dogs.

Changing the values will make the if statemetns react differently depending on which we change.

E.g. changing people = 20 to people = 1 on line one will return

Too many cats! the world is doomed!
The world is drooled on!
People are less than or equal to dogs.
=> nil

Increment operators

This exercise also introduced new assignment operators which update values by incrementation.  So for example X=X+1 could be rewritten more efficiently using the increment operator, assuming X =1.  X+=1  will return 2.










Learn Ruby the Hard Way, Exercise 30: Else and If

The last exercise introduced the if statements that create branches in the code that run when a boolean expression is true.

So for example we could have the code that just prints stuff  e.g. puts “Bananas” encapsulated inside an if statement that will only run and puts a string if the condition is true.


x = 1
if x == 1
puts “Bananas”

This excercise adds the else and elsif keywords that can be added to an if statement like below



Which output the following:

We should take the cars.
Maybe we could take the trucks.
Alright, let's just take the trucks.
=> nil


Study Drills

1. Try to guess what elsif and else are doing

an elsif keyword adds a second condition to check if the first condition is not true, ruby will jump to the elsif keyword and check if the conditions it supplies are true, you can add bazillions of elsif’s to an if statement. An else will run if all the conditions provided by the if and elsif are not met.

2. Change the number of cars, people, and trucks and then trace through each if-statement to see what will be printed.

Like before in the last exercise, changing the values  of the variables meant different parts of the if statements were true and others weren’t so different strings were printed out.

3. Try some more complex Boolean expressions like cars > people || trucks < cars.

I added this to line 5 of the code as below

if cars > people || trucks < cars
puts “We should take the cars.”

elsif cars < people
puts “We should not take the cars.”
puts “We can’t decide.”

As cars has a higher value than people the first part of the || expression was evaluated and ruby never checked the second half to see if trucks < cars. Either operand in a || expression can be true for it to evaluate to true.

4. Above each line write an English description of what the line does.

Sure here you go

ex30 annotated


A few other bits I picked up:

If none of the conditions in an if statement are true the program will continue to run and jump the end keyword and carry on. If two or more conditions are true, Ruby will just evaluate the first one it finds that is true, execute the associate code block and move to the end keyword.

Also on an unrelated point about the to_integer string method; whilst making an experiment (below) when I supplied gets.chomp with ‘bananas’ instead of either an integer the .to_i  returned the integer 0!



number = gets.chomp.to_i

if number > 0
puts “Number is greater than zero”
elsif number < 0
puts “Number is less than zero”
elsif number == 0
puts “Number is zero”


Number is zero
=> nil

Learn Ruby the Hard Way, Exercise 28: Boolean Practice.

This exercise has you go through using the Boolean and comparison operators from the last exercise ( &&, ||,  !,  !=,  =) and solve a table of Boolean logic expressions below:

  1. true && true
  2. false && true
  3. 1 == 1 && 2 == 1
  4. "test" == "test"
  5. 1 == 1 || 2 != 1
  6. true && 1 == 1
  7. false && 0 != 0
  8. true || 1 == 1
  9. "test" == "testing"
  10. 1 != 0 && 2 == 1
  11. "test" != "testing"
  12. "test" == 1
  13. !(true && false)
  14. !(1 == 1 && 0 != 1)
  15. !(10 == 1 || 1000 == 1000)
  16. !(1 != 10 || 3 == 4)
  17. !("testing" == "testing" && "Zed" == "Cool Guy")
  18. 1 == 1 && (!("testing" == 1 || 1 == 0))
  19. "chunky" == "bacon" && (!(3 == 4 || 3 == 3))
  20. 3 == 3 && (!("testing" == "testing" || "Ruby" == "Fun"))


I wrote down what I thought each would evaluate to  ran it through Irb to get he answers. Spoilers ahead!

  • true && true   #=> TRUE
  • false && true  #=> FALSE
  • 1 == 1 && 2 == 1  #=> FALSE
  • "test" == "test"   #=>  TRUE
  • 1 == 1 || 2 != 1   #=>  TRUE
  • true && 1 == 1   #=> TRUE
  • false && 0 != 0  #=>  FALSE
  • true || 1 == 1   #=>  TRUE
  • "test" == "testing"  #=> FALSE
  • 1 != 0 && 2 == 1   #=> FALSE
  • "test" != "testing" #=> TRUE
  • "test" == 1  #=> FALSE
  • !(true && false)   #=> TRUE
  • !(1 == 1 && 0 != 1)   #=> FALSE 
  • !(10 == 1 || 1000 == 1000) #=> FALSE
  • !(1 != 10 || 3 == 4) #=> FALSE
  • !("testing" == "testing" && "Zed" == "Cool Guy") #=> TRUE. Lol
  • 1 == 1 && (!("testing" == 1 || 1 == 0)) #=> TRUE
  • "chunky" == "bacon" && (!(3 == 4 || 3 == 3)) #=> FALSE
  • 3 == 3 && (!("testing" == "testing" || "Ruby" == "Fun")) #=> FALSE

This exercise was actually fun and after a bit of practice (I had a lot on codecademy) you can whiz through these if you remember to evaluate stuff inside the parentheses first.




Learn Ruby the Hard Way, Exercise 27: memorising Logic.

This exercise was all about logic and the different operators you can use in  Ruby to determine if a statement is true or false. I get the idea (so far…) that pretty much everything in Ruby is either true or false and most of the time the statements written check to see if a condition is true, if it is then the block of code following will be evaluated and if false then the program moves onto the next block.

This exercise introduced three Boolean operators that we can use to check if something in Ruby is true or false:

&& – ‘AND’

&& checks evaluates to true when both operands are true, for example:

true && true     #=> true

true && false    #=> false

|| – ‘OR’

|| will evaluate to true if either of the operands are true

false || true      #=> true

true || true      #=> true

false || false     #=> false

! – ‘NOT’

! reverses true and false values which is pretty cool.

!(true && false)   #=> true

!true   #=> false

!false  #=> true

Ex27 also showed us some new comparison or relational operators:


Checks to see if two operands are equals like below

true == true   #=> true

false == true  #=> false

42 == 42  #=> true

‘thirty’ ==  30 #=> false


Checks to see if two operands are not equals like below:

40 != 41  #=> true

“Bananas” != true   #=> true

1 != 1   #=> false


This exercise introduced the truth table to memorise  below. Honesty I’ve spent a lot of time already on Codecademy memorizing these so skipped ahead to exercise 28.

NOT true?
!false true
!true false
OR (||) true?
true || false true
true || true true
false || true true
false || false false
AND (&&) true?
true && false false
true && true true
false && true false
false && false false
NOT OR true?
not (true || false) false
not (true || true) false
not (false || true) false
not (false || false) true
NOT AND true?
!(true && false) true
!(true && true) false
!(false && true) true
!(false && false) true
!= true?
1 != 0 true
1 != 1 false
0 != 1 true
0 != 0 false
== true?
1 == 0 false
1 == 1 true
0 == 1 false
0 == 0 true


Learn Ruby the Hard Way, Excercise 26: Congratulations, Take a Test!

This excercise has you go through some very poorly written code (the author has actually gone through the code from the last two exercises and deliberlty butchered them making lots of typos.) Finding all of them actually took some time about half an hour in the end of running the program repeatedly through irb.

Here is the pre-corrected code, looks innocuous enough…

module Ex2

# This function will break up words for us.
def Ex25.brak_words(stuff
   words = stuff.split(‘ ‘)
   return word

# Sorts the words.
def Ex25.sortwords(words)
   return words.sort

# Prints the first word after popping it off.
df Ex25.print_first_word(words)
   word = words.pop(1)
   puts wor

# Prints the last word after popping it off.
def Ex25:print_last_word(words)
   word = words.pop
   put word

# Takes in a full sentence and returns the sorted words.
def Ex25.sort_sentence(sentence)
   words = Ex25.break_words(sentence)
   return Ex25.sort_words(words)

# Prints the first and last words of the sentence.
def Ex25.print_first_and_last(sentence
   words = Ex25.break_words(sentenc)

# Sorts the words then prints the first and last one.
def Ex25.print_first_and_last_sorted(sentence)
   words = Ex25.sort_sentence(sentence)


puts “Let’s practice everything.”
puts ‘You\’d need to know \’bout escapes with \\ that do \n newlines and \t tabs.’

poem = <<END
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.

puts “————–“
puts poem
puts “————–“


five = 10 – 2 3 – 6
puts “This should be five: #{five”

def secret_formula(started)
jelly_bens = started * 500
jars = jelly_beans / 1000
crate = jars / 100
return jelly_beans, jars, crates


start_point = 10000
beans, jars crates = secret_formula(start_point)

puts “With a starting point of: #{start_point}”
puts “We’d have #{beans beans, #{jars} jars, and #{crates} crates.”

start_point = start_point / 10

sentence = “All good things come to those who wait.”
words = Ex25.break_words(sentence)
sorted_words = Ex25.sort_words(words)
Ex25.print_last_word words)
sorted_words = Ex25.sort_sentenc(sentence)

And here are the corrections I found after going over it with a fine toothcomb and running it through powershell



Here is wha the output should have looked like:

You'd need to know 'bout escapes with \ that do 
 newlines and 	 tabs.
	The lovely world
with logic so firmly planted
cannot discern 
 the needs of love
nor comprehend passion from intuition
and requires an explanation

		where there is none.
This should be five: 5
With a starting point of: 10000
We'd have 5000000 beans, 5000 jars, and 50 crates.
=> nil



This exercise wasn’t actually too hard although some of these mistakes jump out at you a lot easier and often the simple typos were the hardest to spot!


Learn Ruby The Hard Way, Excercise 25: Even More Practice

In this excercise we created the .rb file contain a bunch of different methods which we can run in irb using the a new thing called the module.


In the code above all the methods between the the module keyword on line 1 and end on 46 can be accessed in irb by typing: %require “./ex25.rb” if the file exists this will return true if it does exist. This exercise has you create a a string whilst in irb and run the different functions from Ex25.rb, below is the input:

require "./ex25.rb"

sentence = "All good things come to those who wait."
words = Ex25.break_words(sentence)
sorted_words = Ex25.sort_words(words)
sorted_words = Ex25.sort_sentence(sentence)

I’ve created a table to try and work out what each part does:


This was the excercise run through irb(I made a mistake on line 11 i had to blot out!)



Study Drills

Take the remaining lines of the What you Should See output and figure out what they are doing. Make sure you undersatand how you are running your functions in teh ex25 module.

Already done.

The ex25 module doesn’t have to be in a file named ex25.rb. Try putting it in a new file with a random name, then import that file and see how you still have Ex25 available, event though the file you made does not have the Ex25 in it.


Try breaking your file and see what it looks like in irb when you use it. You will have to quit irb with quit() to be able to reload it.

Changing the code on line one, ‘Ex25’ to ‘ex25 returns a syntax error : ‘class/module name must be CONSTANT’  – it turns out modules and classes are constants, which have to start with a uppercase letter.



This exercise was interesting and introduced modules to run programs inside other RB files rather than having all you code in one huge unwieldy file and also I started learning a bit about constants.

Learn Ruby The Hard Way, Exercise 24: More Practice

The title of the exercise pretty much sums up what it was about –  more practice. Here is the code for ex24:

ex 24

Study Drills

Make sure to do your checks: read it backward, read it out loud, and put comments above confusing parts

The heredoc used to put the awful poem from lines 3-8 was quite interesting, for now all I know is that it functions the the same as “”” to put multi line strings and also supports string interpolation.

In the online version of this exercise the author added an extra bit of code on lines 33-35. Line 35 uses a C style of putting variables into Ruby strings.  After playing around with how exactly the %s and %d work and what they mean, I concluded I don’t have a clue how they work, moving swiftly on.

Break the file on purpose, then run it to see what kinds of errors you get. Make sure you can fix it.


I’m quite good at breaking things so I tried this a few different ways:


First I removed the Keyword Def for secret_formula method which returned:

ex242.rb:27: syntax error, unexpected keyword_end, expecting end-of-input

Ruby wasn’t expecting the keyword end as it had no def-end pair to tell it we were creating a new method.




I removed the end keyword from the heredoc which gave me two messages, this is telling us the program can find the END keyword for the heredoc it was expecting before the end of the file.

ex242.rb:38: can’t find string “END” before EOF

ex242.rb:5: syntax error, unexpected end-of-input, expecting tSTRING_CONTENT or tSTRING+DBEG or tSTRING_DVAR or tSTRING END

The End keyword can be anything you like (upper or lowercase, letters and numbers)  so long as it matches the start, so for instance we could write

poem = <<TEST

This is some text





And deleting line 31 which meant that we got the following error messages as the string interpolation of #{beans} on line 34 had nothing to work with.

ex242.rb:34:in ‘<main>’: undefined local variable or method ‘beans’ for main:Object <NameError>


Learn Ruby the Hard Way, Exercise 23: Read Some Code

Study Drills

  • Goto Bitbucket.org, github.com, or gitorious.orge and search for “Ruby” Pick a random project
  • Click on the source tab and browse through the list of files and directories until you find a .rb file

I went to Github and searched for ‘Ruby Project’ and found the below in a random rb file in a ruby project someone was making to teach how to a bank account program.

Here is the code:

ex23 code 2

  • Start at the top and read through the code, taking notes on what you think it does.

ex23 code.png

  • if any symbols or strange words seem to interest you, write them down to search later.

attr_reader, include, .inject, self.class,


There’s a few things I researched but don’t really know how to use properly yet like attr_reader….however I did look up and learn about classes and objects which was most satisfactory.