This document provides an introduction to programming concepts like numbers, strings, variables, and methods through examples and exercises in Ruby. It is intended to teach programming basics to kids and adults. The document covers fundamental data types like integers and floats, strings, variables and how they store values in memory, basic math operations, and introduces string methods. Each chapter includes examples and practice problems to reinforce the concepts. Later chapters will cover more advanced topics like collections, files, and enumerables.
2. 1. Introduction
2. What is Programming?
i. Instruction Set
3. Numbers
i. Practice
4. Strings
i. Practice
5. Variables
i. Practice
6. If and Else
i. Practice
7. Loops
i. Practice
8. Collections
i. Array
ii. Hash
iii. Practice
9. Methods
i. Writing a Method
ii. Create a File
iii. Method with Argument
iv. Practice
10. Enumerables
i. Each
ii. Each_with_index
iii. Select
iv. Map
v. Practice
11. Files
i. The End
12. Answers to Practice Problems
13. Appendix
Table of Contents
3. This book is for any kids that want to learn how to code. Adults are welcome too.
With ten simple chapters, you will learn the basics inherent in all fundamental programming languages: variables, strings,
numbers, methods, collections and more.
These are the basic building blocks used in modern programming languages today. By the end of this book, you will
have learned what all these terms mean and how they are used to design a computer program.
Let's get started!
4. Programming is language. We use language to communicate with our friends. We use programming to communicate with
our computers.
A program is nothing more than a set of instructions for the computer to execute. These instructions outline the plan or
project, like a blueprint for a house. Without a blueprint, the builders wouldn’t know what the architect wants, just like the
computer doesn’t know how to create what you want without a program.
Learning a programming language is a lot like learning any language. First you start with the basic building blocks--the A,
B, C's. Then you start learning how to put those blocks into words, sentences, and eventually commands that will tell your
computer what to do.
What is programming?
5. Why do we need to speak a strange language to communicate with computers?
Computers are a bit like dogs. They are great companions, but you need to give them commands to tell them what you
want them to do. There are a lot of different programming languages, just like there are a lot of foreign languages.
However, just as there are similarities in German, French or Spanish, there are similarities across programming
languages, like JavaScript, Ruby or Python.
This book will help you learn the basics of programming, using the Ruby language. The building blocks you learn in this
book will help you learn any other programming language.
Each chapter will go into more detail with basics at the beginning and more complicated material at the end. For now,
let’s get started with some simple ideas.
Integers, Floats and Strings...and maybe Ice Cream
Before we can understand how to write programs, we need to understand data. Data is simply information that you can
input (give), output (get), store or manipulate with a computer. The two fundamental types of data used in almost every
programming language are numbers and strings.
Numbers come in two tasty flavors. Integers, which are whole numbers without a decimal point, and floats, numbers that
contain a decimal.
For example, these are integers:
1, 7, 0, 13, 2000
And these are floats:
1.2, 3.14, 5.12345, 0.35
Every time you see a whole number like 8 or 19 you will know they are integers, and every time you see a number with a
tasty sprinkle, or decimal, they will look like this: 3.4 or 8.1 and you will know they are (root beer) floats.
Simple, right? Ok, let's keep going.
The second type of data, or information given to a computer, are called strings. What’s a string? "Anything between
quotes is a string." Since that last sentence was inside of quotes, it was technically a string! You probably see strings all
the time without even realizing it!
6. For example, have you ever seen an alert message on your computer saying something like this:
Somewhere inside a program or web application, an engineer wrote the sentence "File does not exist!" and put it in
quotes to create a string. When you were alerted with the pop up box, that string was printed to the screen.
Strings are a little bit like backpacks or lunch pails, they are great for storing all the stuff we care about in an easy-to-carry
container. Except with a string, the straps are the quotes. We use strings to store words, sentences, and even files. Here
are some examples of strings:
"I'm a string!"
"And_so_am_I"
"9"
"This long paragraph is even a string.nAnd it has these
strange n things that we'll explain later."
9 is such a joker. Did you notice we put the number nine as a string? This is very different than the actual number nine,
but we will get to that later.
Now that you know the two most fundamental pieces of data the computer uses (numbers and strings), it's time to dive a
bit deeper into each of these data types.
7. Do you know basic math? Great, so does Ruby! Ruby uses the same adding, subtracting, multiplication and division that
you do.
2 + 2 => 4
9 - 3 => 6
2 * 3 => 6
4 / 2 => 2
Ruby can also perform logical operations, such as greater than > and less than < .
4 > 2 => true
7 < 2 => false
3 >= 3 => true
0 <= 1 => true
You can try these simple commands yourself, but first you need to have Ruby installed on your computer.
Installing Ruby
If you’re using Mac OS X, Ruby is already installed. Hooray! Just open your Terminal application. To find terminal you can
click the magnifying glass in the top right corner of your screen, then type Terminal and click the first result. (Or you can
navigate to Applications - Utilities - Terminal and double click).
If you’re using Linux, open up a shell, type irb and hit enter. And if you’re on Windows, open fxri from the Ruby section of
your Start Menu.
As a third option, check out Repl.it (http://repl.it/languages/Ruby). This is a pretty fantastic tool that allows you to type code
into your web browser. No installation required!
Next, type the letters irb into the terminal or shell screen and hit enter.
So, what is IRB anyway?
IRB stands for Interactive Ruby Shell. An Interactive Ruby Shell is like a little secret fort located inside your computer. You
can use your IRB environment to play around with Ruby and learn different commands. Open up IRB (from a shell
window or using www.repl.it/languages/Ruby and try typing some of these simple math calculations to see what the
computer returns. Or try your own!
2 + 2
4 < 7
5 > 10
7 / 4
Numbers
8. Curious about the => arrows? Ruby engineers like to call these hash rockets. You will see that typing 3 + 2 or any other
thing into IRB will always return a value, signified by the pointer => .
A bit more math
Programming languages like Ruby can perform a lot of mathematical equations and expressions. Now that we can see
how Ruby performs addition, subtraction, multiplication and division, we'll see how she handles exponents and the oh-
so-cool modulo!
Exponents
Exponents tell a number how many times it should be multiplied. For example, 2 times 2 equals 4, 4 times 2 equals 8. So,
2^3 means 2 times 2 times 2, or 8. Don't worry about exponents if they are unfamiliar to you. They are not necessary to
learn programming! Ruby uses two stars to signify an exponent math expression:
2 ** 3 => 8
3 ** 2 => 9
10 ** 3 => 1000 #10 times 10 times 10!
# Also, the pound symbol is used for comments
# (and ignored by Ruby)
Modulo
In addition to these standard math operations, the computer has something called the modulo operator, which is
represented using a percent symbol: %. The modulo’s job is to find the remainder after dividing one number with another.
The remainder is what is left over, or what remains when you divide one big number by a smaller number. Let's look at an
example.
9 divided by 3 would result in a modulo of 0, because there is no remainder. Since 3 divides evenly into 9 (three times)
there are no numbers left over, and that is why 9 modulo 3 is 0. If we try it again with a different set of numbers, say 9
modulo 2, we would have a remainder (or a modulo operator) of 1. Because 9 divided by 2 equals 8, leaving a remainder
of 1. Try these examples
8 % 2 => 0
9 % 2 => 1
9 % 5 => 4
If exponents and modulos are too complex to understand right now, don't worry. Again, they are not a requirement for
programming. It's important at this stage to simply understand that the computer can do simple math for you. Check out
some examples below.
9. Practice
Try these problems in your head, or on paper. Then see how they work in the Ruby shell (IRB).
1) 2 + 3 + 5
2) 10 - 3
3) 9 / 3
4) 4 * 2
5) 4 ** 2
Now for some harder ones.
6) What is the result of 11 % 5 ?
7) What is 14 % 3 ?
8) A wizard carries two numbers (one even and one odd) in each hand. He won't open his hands to show you, but he will
let you use modulo. Your task is to find out which hand holds an even number, and which holds the odd.
Hint: A number divided by two, with no remainder, is even.
10. Congratulations! You are halfway through learning the two most fundamental 'blocks' of programming code--Numbers
and Strings.
Remember that a string is simply a piece of data (usually words) wrapped in quotes.
In Ruby, we can perform some math-like operations using our friends, the strings. For example, we can multiply a string
like so:
"repeat " * 3
=> "repeat repeat repeat "
In the above example we have a string: "repeat " that we multiply * by three. When Ruby performs the * 3 method it
actually just copies the string three times and pastes the result together. Sort of like this:
"repeat " + "repeat " + "repeat "
=> "repeat repeat repeat "
In fact, you can write either of these lines of code and the result will be the same. Much in the same way that writing 3 + 3
+ 3 = 9 yields the same result as 3 * 3 = 9 . When the computer adds strings together we call it concatenation.
"Cat and " + "Dog"
=> "Cat and Dog"
In the example above, there are two strings, one is "Cat and " and the second string is "Dog" . By giving the command to
add the two strings + , we are able to join both strings together using the magic of concatenation. (Concatenation is just a
fancy old Latin word for join together).
Ready to try it out?
Open Terminal again (or http://repl.it/languages/Ruby) and try multiplying and adding a few strings yourself to get the
hang of it.
Now try adding a number with a string. It didn’t work did it? Remember that joker "9" string from our previous example in
chapter one? Ruby doesn’t see this as the actual number 9, instead it sees a string.
To Ruby, anything that is inside the quote isn’t just a word or a number anymore. Everything inside the quotes is a string.
Strings
11. So when we try to add a string with a number, Ruby gives us an error:
"9" + 9
=> TypeError: can't convert Fixnum into String
In the above example, we would see "9" + 9 and think the answer is 18. But Ruby doesn’t see it like that. Ruby sees
"STRING" + NUMBER . And you can't add strings and numbers, because they are different types of data.
This doesn’t mean we can’t do this sort of equation, it just means we need to use a trick to make sure Ruby understands
what we want. Of course, there are lots of interesting methods or actions we can perform to get Ruby to do what we want.
We’ll look at some of those actions a bit later, but for now, you could solve the above problem by using the to integer
method, or to_i . This would convert the string to a number (more specifically, an integer). And with two numbers, Ruby
can do the math:
"9".to_i + 9
=> 18
Remember those n characters from the first chapter? This is what the computer uses to note a new line in your string. So
the following string:
print "One line.nAnother line.nAnd another.n"
Would print like this:
One line.
Another line.
And another.
In this way, Ruby can store sentences or even whole files inside just one string. Now that you have a better
understanding of strings, check out some examples on the practice page.
12. Practice
What is the result of each of the following?
1) puts "What is the return result" + " of " + "this operation?"
2) "This string minus" - "That string"
3) "1234.55".to_i
4) "1234.55".to_f
5) "Not a number".to_i
6) puts "1n2n3n"
7) Why might it be useful that the to_i (to integer) method return zero for strings that can’t be represented as numbers?
8) What do you think the length method does? "Count".length
9) How about the split method? "Count".split("")
10) What do you think slice does? "Count".slice(2)
Want to see more cool String methods? Just call methods on the String class! Type String.methods into your IRB:
IRB$ String.methods # some of the built-in Ruby methods for String
[:try_convert, :allocate, :new, :superclass, :freeze, :===, :==, :<=>, :<, :<=, :>, :>=, :to_s, :included_modules, :include?,
:name, :ancestors, :instance_methods, :public_instance_methods, :protected_instance_methods,
:private_instance_methods, :constants, :const_get, :const_
and many more...
13. At their simplest, variables are merely storage containers. They help us hold information. You create your own variables,
starting with a lowercase letter followed by an equal sign and its value (usually a number or a string, but sometimes more
complex code can be stored in a variable). You’ve seen this before in math.
x = 12
The value of x is?
=> 12
In Ruby, a variable name is defined once you write (almost) anything left of the equal sign. The equal sign (as in most
programming languages) is used to assign the value to the right, to the variable. Here are a few more examples of
creating variables.
myVar = "my string variable"
a_long_var_name = 42
myCat = "whiskers"
Variable Storage in Memory
With computers, variable storage is slightly different than common math, due to the way memory storage is created. Don't
worry if this section seems complicated, you will start to get the hang of it as you write more code.
In an effort to not waste memory, the computer avoids storing duplicate information. In the following example, each
variable (X, Y and Z) will point to the same place in memory because they store the same value: twelve.
x = 12
y = x
z = 12
In order to store the value 12, the computer creates a location in memory with an address, let's assume the address is
ABC12. In this sense, a variable is like an X on a treasure map, guiding you to the right location.
Yet variables don't actually store their information--they point to it. Or in another way, variables store memory addresses
that store information. In the example above, each variable points to the same memory address that stores the number
12. This way the computer doesn't need to create three different memory locations for one value, it can use ABC12 for all
three.
x = 12 => memory address: ABC12
y = x => memory address: ABC12
z = 12 => memory address: ABC12
Now that you know how variables store information (or memory addresses) see if you can figure out the end value of X:
y = 5
# y points to memory address AB1,
# which contains the value 5
x = y
# x points to memory address AB1
y = 7
# y now points to memory address CD1,
# which contains 7
x equals ?
Variables
14. The trick here is to understand that X does not equal Y. Remember, X only POINTS to the value stored in the memory
address that Y points to (AB1), at the time it was assigned. No matter what happens later to Y, the only thing X needs to
remember is the location of AB1 (which will always be 5 while this program is running).
When we change the value of Y to 7, we are actually telling the computer to create a new memory address that contains
the value 7 and point to it. X does not change its original address, so the value of X remains 5.
There is a built-in Ruby method called object_id that shows the id of the Ruby object. This can be correlated to a kind of
unique memory address. Let’s look at the following example using this method.
y = "test" => y.object_id => 7021
x = y => x.object_id => 7021
At this point, only one memory address needs to be created, since the stored value ("test") is the value for both X and Y.
y = "new" => y.object_id => 8333
x equals? => x.object_id => 7021
Once we change the value of Y, we create a new memory location with a new value stored (the string "new"). X does not
equal "new", it still equals the value stored in the original memory address that it pointed to at the time we set X equal to Y
(the string "test").
When we change variables and add new information, Ruby creates more memory locations with specific addresses--if
none of the current addresses are holding the same information. And actually, Ruby has already created several object
ids to help store common numbers and letters in memory, like the number 12 in our example above.
Don't worry if this is all too confusing. You don't actually need to fully understand this concept to program. As we move
along through the other core concepts of coding you will begin to see how variables work within the bigger picture.
The key point to remember is that an = equals sign in programming means "assign the value to the right of me, to the
name on the left." Visually, that would look like this:
number12 = 12
(variable name) (is assigned) number 12
number12 = 12
15. Practice
1) Store the value of 54 / 3 into the variable x. What is the value of x?
2) Give the value of x (from problem 1) to y, a new variable. Now make x equal to itself divided by 3. What’s the value of
x? What’s the value of y?
3) What if we performed some math on our variables? If we set x to 12, what’s x divided by 3?
4) What’s the value of x now?
16. "If you clean your room then you can play, or else you won’t." - Mom
If and else statements help Ruby understand what you want her to do and when you want her to do it.
So far, we’ve learned how Ruby can perform basic math on numbers, store words and sentences as strings, and place
these types of information into memory stored in variables. Now that we know how to store information and interact with it,
we need a way of telling the computer what to do with that information.
One way we do that is with conditionals. This is why your parents say they love you unconditionally, because there is no if
or else, there is only 100% love, no matter what. Ruby doesn’t love anything unconditionally, Ruby needs to be
convinced by conditions.
A conditional is something that depends on other factors. If this something happens, do that, otherwise, do something
else. For example, if you are hungry, eat a sandwich, else, don’t eat a sandwich!
Here’s how an If Else conditional might look in Ruby.
# set an x variable to the value 5
x = 5
# start the if / else conditional
if x <= 10
puts x
else
puts "Number is greater than 10"
end
In a conditional, the computer checks to see that the code after the if is true. We call this code a block, which just means a
small piece of code that has some function. In this case, our block is X <= 10 .
So, if our block is true (if X is less than or equal to 10), the computer will perform the action in the next line below the if
statement. Since X is equal to 5, it is less than 10, and the value 5 is put on the screen. If X were 11, the conditional (X <=
10) would realize this was a false statement, and the string "Number is greater than 10" would be outputted (shown) on
the screen.
When the computer moves through an if-else conditional, it will follow the instructions under the first if statement that
evaluates to true. It then ignores all other conditions in the if-else conditional.
What is a boolean?
We've just learned how a conditional checks to see if something is true or false . A true or false value is called a boolean
in programming. We could write another conditional in a different way using booleans.
If and Else
17. if false
puts "false"
elsif true
puts "true"
else
puts "This won’t print"
end
Let’s walk through each step to get a better understanding. Nil and False are the only objects in Ruby that are
considered falsy. Something is falsy when it has a false value. Nil is Ruby’s way of representing nothing--nada, zip, zero!
No value stored here whatsoever!
In the example above, the conditional checks to see if false is true. Since the false object will never be true, the computer
moves on to the next line to see if true is true. It is, so Ruby puts the string true to the screen!
The final else will never print, because true will always evaluate to true and so the program exits before getting to the
else line. Remember, Ruby is only looking for the first true if statement, ignoring everything else.
Here are the basic elements used to evaluate conditionals:
< # less than
> # greater than
<= # less than or equal to
>= # greater than or equal to
== # equal to
!= # not equal to
When checking if an object is less than or greater than, we use the same symbols found in math. When checking if some
object is equal to another object, we use two equal signs. In Ruby, like many programming languages, one equal sign is
used to assign or give a value to a variable. If we want to check that an object is not equal we use an exclamation mark
before the equal sign.
What's an object?
You may have noticed that we keep talking about things as objects. To understand a code object think about an object in
real life. A ball, a book, or even your dog--these are all different types of objects or physical things. In programming, we try
to represent real life objects with code objects.
For example, if you walk the dogs in your neighborhood, you may know their names in your head. Rex, Sparky, and Spot.
But how would a computer know their names? Well, we could represent each dog as a string object in Ruby, like so:
["Rex", "Sparky", "Spot"]
In fact, this line of code is actually four objects! Can you see why? We have Rex, Sparky and Spot, that makes three
objects. But we also have the list of dogs, which is another object! This is the neat thing about Ruby, everything is an
object. Let me say that again.
Everything is an object
That means that every thing you have learned so far was a type of object. Numbers, strings, variables, if statements,
booleans and even code blocks (such as X < 10)...these are all objects! Next chapter we'll learn about Loops. (Yep, loops
are objects too). Don’t worry, these aren’t the roller coaster type of loops.
18. Practice
What would the computer say? Try to do these in your head before going to IRB. Remember, the answers will be a
boolean value, either true or false.
1) Is 3 > 5 ?
2) 3 < 5
3) 5 == 5
4) 10 >= 10
5) 10 <= 12
6) 10 != 10
7) 10.object_id == 10.object_id
What about strings?
8) "dog" == "cat"
9) "cat" == "cat"
10) "cat.object_id" == "cat.object_id"
19. At its most basic level, a loop is when a computer repeats a specific task. A computer is kind of like a robot, because you
can make it do lots of things very quickly. When you give it a loop, you're telling the computer to repeat a task over and
over. Since the computer can perform thousands of operations within a second, loops become very powerful. Let’s look at
a previous code example again to help us understand loops.
x = 0
while x < 5
puts x
x = x + 1
end
puts "Finished the while loop."
This is called a while loop. The statement after the word while must be true for the loop to continue running. In this
example, we set x to the value zero. Our while loop checks to see if our statement is true: x variable is less than 5 and it is!
So, the computer executes the code (follows our block of instructions) between while and end until X is no longer less
than 5.
This loop tells the computer to perform a task WHILE certain things are happening. Your parents would tell you to look
both ways, while you cross the street. In a way, you are being programmed to perform the task of looking both ways
before crossing the street. If there are no cars, it's safe to cross.
The word puts is a method that simply "puts" the following content to the screen. Technically, it means put string and
takes a string argument to put on the screen.
Here is some pseudo code to see what's happening in our while code.
# pseudo code
1) x is 0
2) Is 0 less than 5? True. puts x. x = 0 + 1. x is 1.
3) Is 1 less than 5? True. puts x. x = 1 + 1. x is 2.
4) Is 2 less than 5? True. puts x. x = 2 + 1. x is 3.
5) Is 3 less than 5? True. puts x. x = 3 + 1. x is 4.
6) Is 4 less than 5? True. puts x. x = 4 + 1. x is 5.
7) Is 5 less than 5? False. Loop ends.
8) "Finished the while loop." is printed to the screen.
In this example, the x variable is set to zero outside the while loop. When the while loop begins, the computer checks to
see if x is less than 5. Since 0 is less than 5, this is a true statement and the computer moves on to puts x, which displays
the value of x to the screen. The next operation is to assign x the value of x + 1 (in this case 0 + 1). When it gets to the
end, the loop repeats to see if x is still less than 5. Since 1 is less than 5, we put 1 to the screen and assign x the value of
1 + 1, and the process continues. Once x is equal to 5, the loop stops because the statement (5 < 5) is no longer true, it's
false. After exiting the loop the computer executes the final puts statement.
The end result looks something like this:
0
1
2
3
4
Finished the while loop.
Loops
20. While loops are great for counting, but they can be used in other ways as well. For example, what if we played a game
that wouldn’t let the player move forward unless they got the right answer?
answer = "" # creating an empty String variable
while answer != "Ruby"
puts "Sorry, wrong answer." unless answer == ""
puts "What is the best programming language?"
answer = gets.chomp
end
puts "That's right!"
We are using a few new Ruby vocab words, or methods: gets and chomp . Don't worry, we will get to methods later, but
here's what's happening.
In the example above, the computer will continue to prompt the user for "the best programming language" until the
answer equals "Ruby". We assign the users answer to the variable answer using the built-in Ruby method gets . Gets is
like a little helper monkey that helps the computer "get" a piece of information that is entered into the terminal.
Chomp is also a method. Its special task is to remove the last new line character. When you hit enter the n new line
character get stored, but chomp will remove it.
Gets and chomp are merely methods we use to cleanly assign the user’s input to the answer variable (without that
strange new line character). Once the user enters the right answer, the computer exits the loop and ‘That’s right!’ is
printed to the screen.
We can look at another example using a for loop.
for number in 1..5 do
puts "The current value is #{number}"
end
The for loop starts without a true condition being met. This loop will execute the code block between do and end once for
every number in the range 1 through 5 (that's the 1..5 part). The word number is just a temporary variable that represents
each item within our for loop range. For example, a range of 2 through 8 would be written 2..8. A range of 1 through 25
would be written 1..25. Easy, right?
The funny number sign and curly brackets is a string interpolation. We will cover this later, but all you need to know right
21. now is that it places the value of our number variable inside the string. The output would look like this:
The current value is 1
The current value is 2
The current value is 3
The current value is 4
The current value is 5
Hopefully you are beginning to see the power of loops in Ruby. There are a few other loops, but while and for are the
standard ones to start with. When we combine loops with collections, our programs become even more valuable!
Imagine a comic book collection, or a marble collection, or a toy collection. They are full of individual comics or marbles
or toys. Imagine how much easier it would be to count, sort and organize our collections if we had the super fast
computers helping us while we do other things! Next, we’ll show you how to get Ruby's help in handling collections. For
now we'll finish the chapter with some examples.
22. Practice
Let’s pretend we’re at a medieval castle, patiently waiting for our wizard to arrive at sunset. Upon every hour we check to
see if our wizard has arrived. We could represent this as a piece of code. More specifically, we could write this as a while
loop. Let’s assume the sun sets around 7pm, and we start waiting on the beach at 5pm.
sunset = 7
current_time = 5
We create a variable called sunset and give it the value 7. We do the same for current_time and set it to 5.
while current_time <= sunset do
puts "Still waiting for the wizard."
puts "It’s now #{current_time} o’clock"
current_time = current_time + 1
end
puts "The wizard has arrived!"
This while loop would result in this output:
Still waiting for the wizard. It’s now 5 o’clock
Still waiting for the wizard. It’s now 6 o’clock
Still waiting for the wizard. It’s now 7 o’clock
The wizard has arrived!
1) What’s the current value of the current_time variable?
23. In order to store data, we use collections. There are two basic ways we store our data collections. One is called an Array,
the other is called a Hash. You can think about a collection of data like a trunk of toys.
Let’s start with the Array toy chest first.
Collections
24. Arrays are ordered, indexed collections of data that can have various types. An ordered collection means that it is "in
order". When you line up with your classmates at school in a lunch line, you are a collection of kids in an ordered line.
Arrays are kind of like that. You can order the line of kids in many different ways. You could order from tallest to shortest.
You could line up in oldest to youngest, or you could line up in shortest hair to longest hair. No matter which way you
lined up the kids, you’d still be in some kind of order. In code, you’d be in an Array.
Let’s say there was a line of kids: Adam, Billy, Molly and Sally. This line of kids is in alphabetical order, with Adam in front
followed by the rest. That means that Adam is number 1, Billy is number 2, Molly is number 3 and Sally is number 4.
These are four kids in an ordered line. If we were to write this as an array, it would look like this:
["Adam", "Billy", "Molly", "Sally"]
Arrays are noted using square brackets, with indexed elements separated by a comma. When a collection is indexed, it
means that each item has a specific number that relates to its order in line. The tricky part to remember is that computers
start their index at zero. This means that Adam’s index is 0, Billy is 1, Molly is 2 and Sally is 3.
One way to think about indexes is distance. Adam is first in the array, so he is zero units away from himself. Billy is next,
only 1 unit away from Adam. Molly is 2 units away, and Sally is 3 units away from Adam. You could also think of array
indexes like a number line, which also starts at zero.
Here’s what our array looks like with its index.
kids_array = ["Adam", "Billy", "Molly", "Sally"]
# kids_array index => [0,1,2,3]
If we want the first element in our ordered array, we look it up by the first index. The first index in any array is zero. We can
find an element by its index using the [ ] method.
kids_array[0]
=> "Adam"
You can think of the brackets like big monkey paws, they clamp down on both sides of the element (whatever the object)
and hold it. If you type kids_array[0] you are asking Ruby to get the first spot. In this case, Ruby would tell you that Adam
is at index zero.
We can also use the [ ] method to add or change an element in our array. For example, if Sally left to another school and
Terry replaced her spot, we could remove Sally and replace her with Terry by using the [ ] method on the correct index
number.
kids_array = ["Adam", "Billy", "Molly", "Sally"]
kids_array[3] = "Terry"
kids_array
=> ["Adam", "Billy", "Molly", "Terry"]
We can even add a new member to our array, like so.
kids_array[4] = "Zoe"
kids_array
=> ["Adam", "Billy", "Molly", "Terry", "Zoe"]
Arrays can contain numbers, strings and even other arrays!
Array
25. number_array = [1,2,3,4,5]
string_array = ["Frank", "Suzy", "Doug", "Jane"]
mixed_array = [number_array, "a string", 13]
If we had an array inside another array, we can use the square brackets in a similar way to access our data. In the
example below, in order to grab the number 2, we use square brackets to access the first element in our array (which is
another array). We then use another bracket to access the number two, the second element in that array.
lots_of_arrays = [[1,2],"string","test"]
lots_of_arrays[0][1]
=> 2
Ruby gives us some cool methods to call on arrays, like sort . When we call the sort method on our string_array, Ruby
sorts our array alphabetically. In Ruby, whenever we use the sort method, the computer understands we want to see the
entire array alphabetized.
string_array.sort
=> ["Doug", "Frank", "Jane", "Suzy"]
However, unless we call sort! on the array, the order will not change permanently and our array will stay in its original
state. When we ask to sort without an exclamation mark, only the result is sorted (not the actual array). When we call
sort! with the exclamation mark, the actual array is sorted in the new alphabetized order.
string_array
=> ["Frank", "Suzy", "Doug", "Jane"]
string_array.sort!
=> ["Doug", "Frank", "Jane", "Suzy"]
Before we get into more examples about arrays, it’s important to mention one of Ruby’s widely used array methods--the
shovel. The shovel is written with two less-than symbols << that are used to insert items to the end of an array. Let’s take
the example above and add Bill to our string array.
string_array
=> ["Doug", "Frank", "Jane", "Suzy"]
string_array << "Bill"
=> ["Doug", "Frank", "Jane", "Suzy", "Bill"]
We could have added Bill with the push method as well.
string_array.push("Bill")
=> ["Doug", "Frank", "Jane", "Suzy", "Bill"]
The shovel method is favored by Rubyists and it’s good to know how it works. More examples on arrays in the practice
section.
26. The next type of collection in Ruby is the Hash. Sometimes called a dictionary, a hash is an unordered list of key value
pairs. A hash is more like a messy room than an array, which is very organized. With a hash, our list of items come in
pairs, placed in any order.
In hash collections, we use curly brackets { } wrapped around pairs of information separated by a comma, { "like" =>
"this" } . The item to the left of the arrow => is the key and its value is the element on the right.
Hashes are extremely useful when we have multiple numbers of similar items in a list. For example, if you used a hash to
organize your toy chest, it might look something like this:
toy_chest = {
"sea_monkeys" => 12,
"dolls" => 5,
"legos" => 514
}
Each of these items is located in our toy chest, and the number of them is represented in the hash. So we have three keys
(sea_monkeys, dolls and legos) with their corresponding values (12, 5 and 514). To access information in this hash, we
can use brackets like we did for arrays.
toy_chest["sea_monkeys"]
=> 12
toy_chest["dolls"]
=> 5
toy_chest["legos"]
=> 514
To add an item to our toy chest hash, we can simply use brackets in a similar way that we did above to retrieve
information.
toy_chest["toy_cars"] = 7
=> 7
toy_chest
=> {"sea_monkeys" => 12, "dolls" => 5, "legos" => 514,
"toy_cars" => 7}
By writing "toy_cars" in brackets next to toy_chest, we’ve actually called a method on our hash, giving it a new key value
pair of "toy_cars" => 7 . To remove an element, we can call the delete method. Don’t worry too much about methods right
now, we just want to show you how easy it is to handle data in your array or hash collections.
toy_chest.delete("sea_monkeys")
=> 12
toy_chest
=> {"dolls" => 5, "legos" => 514, "toy_cars" => 7}
There are several other ways to add, remove and manipulate data in our hash collection. But before we understand these
methods, we need to learn about methods in general. Check out some examples of using a Hash and then, onward to the
next chapter!
Hash
27. Practice
1) Put the following kids in an array. Joe, Sally, Tom, Mary, Doug. Now sort them alphabetically using a standard Ruby
method. What's the resulting array?
2) With your kid_array from question 1, separate the boys and girls into their own arrays. Then put your two new arrays
into one array called "group". What is the least amount of lines required to write this code?
3) Now you should have one "group" array with two arrays nested inside. How might we reverse the order of each array?
Hint: Ruby methods tend to be named by what they do.
4) Our class group has added one student, Tiffany. Add her to the girls list in our group array. What does our array look
like now?
5) Imagine our list of boys and girls is much larger than just three. If each class can only have an equal number of boys
and girls, how might a teacher ensure her lists are equal? Hint: You can use the count method to count the number of
elements in an array.
1) Create a hash for the Wizard’s magic bag. Inside the bag, we’ll put 3 frogs, 5 herbs, and 10 scrolls. Assign the hash to
the variable "bag". What does your hash look like?
2) Remember, hashes consist of key value pairs of any data, not just numbers. Let’s add a wizard’s spell and its result
(which the wizard can never seem to remember). Add a spell to our wizard’s bag with the key: "shazam" and the value
"turns subject into a frog". Now what's in our bag?
3) Our wizard has a change of heart and decides he never wants to turn anyone into a frog. How can we remove the spell
"shazam" from our wizard bag?
4) Our wizard has recently acquired 3 different types of potions. 4 orange potions, 5 blue potions and 7 red potions. How
might we add another hash of potions to our bag?
Hint: remember that we can have collections within a collection.
5) Now that our bag has four keys (frogs, herbs, scrolls and potions), we can use these keys to access our data. In order
to make a new spell, our wizard needs 2 frogs, 3 herbs, 1 scroll and 2 blue potions. How can we remove these items from
our hash?
Hint: We can set the value of a key item to itself, minus how many items removed.
Arrays
Hashes
28. A big part of programming is simply breaking down large problems into smaller and smaller instructions that can work
together to create a solution. Let’s think of this using a real world example. Imagine you are playing baseball and its your
turn to bat. This critical moment when you swing and hit the ball for a home run can be seen as many smaller moments
that led to the big play.
First you picked up a bat. Then you took a few practices swings. Then you walked up to the plate, you readied your
stance, looked at the pitcher. Finally, you took a breath and swung! Each of these small steps can be seen as methods
(small chunks of instructions) that you gave to your body to get a home run.
We can look at methods another way. When you play a video game and reach a new level, there may actually be real
methods that are called by the game. Perhaps the game contains a life_count method that counts how many lives you
have left. Another method could tally up your current score. A third method may calculate your character's current state of
health. Each of these methods would take input from your actions in the game, and go back and get information from the
program to keep everything updated and accurate.
Methods
29. To understand methods a little better, let’s jump into writing one ourselves. Here’s a very simple method you can write
yourself that merely puts information to the screen. You can write a method inside IRB without creating a new file.
In your terminal type irb:
$ irb # type irb to open the ruby interpreter
irb(main):001:0> def hello
irb(main):002:1> puts "Hello World!"
irb(main):003:1> end
=> nil
In Ruby, we define a method using the def keyword. The next word after def is the name of our method. This would be
our hello method, which takes no arguments (kind of like your parents at bedtime). We’ll explain arguments in a moment.
Like at the end of a movie or bedtime story, the word end in Ruby means the same thing as it does to you--that this is the
end of our method. Any code in between our def and end keywords will be run by the computer for this particular method.
This code is our "block" we give the method to execute.
To run our method, we simply call its name hello by typing it into the terminal prompt.
irb(main):004:0> hello
Hello World!
=> nil
In order to write and save several methods, it will be easier to create a file and run the code inside the file, so let’s do that.
Exit the terminal by typing exit .
Writing a Method
30. Open up a text editor. I like using Sublime Text, but you can use any kind. There are several free text editors for download
online. Or you can use repl.it without saving.
Create a new file and type in the method we wrote earlier.
def hello
puts "Hello World!"
end
Save this file as hello.rb to your desktop. Now you can run this file from your terminal. In your terminal, navigate to the
Desktop directory using cd , the change directory command.
If you don’t know how to find your file from the terminal console, I can help you with a simple trick. Just type the following.
(This will take you to your root folder and then to your desktop).
Your-Computer-Name:$ cd
Your-Computer-Name:$ cd ~/Desktop
Your-Computer-Name:Desktop $
Now that we are in the Desktop directory, where our hello.rb file is stored, we can run our Ruby file using the ruby
command! Type ruby hello.rb into the console. It may look something like this.
Your-Computer-Name:Desktop $ ruby hello.rb
Your-Computer-Name:Desktop $
If you had no errors and no output, then your program ran as expected. Great job!
But wait, why didn’t it put "Hello World!" to the screen? Well, this is because our hello method was not called. We simply
ran a program that contained our hello method, but we didn’t specifically call upon that method to be run by the computer.
We can fix this by updating our hello.rb file.
def hello
puts "Hello World!"
end
hello()
Now when we run hello.rb, our hello method is called on line 5. We call a method by simply writing the name of the
method. The parenthesis are optional, because this method has no arguments. If there were arguments, or inputs into our
method, we would put them inside the parenthesis. Now when we run our program, we should see output like this:
Your-Computer-Name:$ ruby hello.rb
Hello World!
Your-Computer-Name:$
Congratulations! You just ran your first Ruby program with its very own method. It ran successfully and outputted "Hello
World!" to the screen using Ruby’s built in puts method.
Now let’s try writing a method that takes an argument.
Create a File
31. What if we want to multiply any two numbers together using our own method. We could write something like this.
def multiply(num1,num2)
num1 * num2
end
We define our method as multiply and pass in two arguments using parenthesis (num1 and num2). Then we can simply
use Ruby’s multiply operator (the * method) on both numbers. The result is returned since it is the last line in our method.
(In Ruby, the last line of a method is returned by default.)
multiply(2,3)
=> 6
multiply(4,2)
=> 8
multiply("Hi",3)
=> "HiHiHi"
Uh oh, looks like our method can multiply more than numbers! We can modify our code to ensure our users enter
numbers, but let’s not worry about that now. How about another way to use arguments for a method. What if we want to
calculate how many days old we are?
def years_to_days_old(years)
result = years * 365
puts "You are #{result} days old!"
end
Let's go over the method we wrote above. First, our method name is set to years_to_days_old . It takes one argument as
input, stored in the variable years . The first line of our method creates a new variable result and assigns it the value of
our passed-in argument years , multiplied by 365. This gives us the number of days per years. We then simply put the
string "You are x days old!" to the screen, where x is our result variable.
Here's what it might look like if we call the method and pass in 10 years as the input.
years_to_days_old(10)
You are 3650 days old!
=> nil
Our puts method outputs the string using interpolation (the #{ } part) to display the result in our answer string. String
interpolation is when Ruby allows a piece code to exist inside a string. This can be a variable or even math, written with a
pound sign and curly braces #{ } . Here are some examples to get the idea.
x = 15
puts "This string has the #{x} variable inside."
=> This string has the 15 variable inside.
puts "This one is doing math: #{x + 5}"
=> This one is doing math: 20
We could add more functionality to the years_to_days_old method and remove the argument input. If we use Ruby’s gets
method we can capture the input from a user’s response. We call chomp to remove (or chomp and eat) the new line
character like we did in a previous chapter. The to_i method turns the user’s string input into an integer. Our method
might look something like this.
Methods with args
32. 1. def years_to_days_old
2. puts "How old are you in years?"
3. years = gets.chomp.to_i
4. days = 365 * years
5. puts "You are #{days} days old!"
6. end
Let’s run this from our IRB terminal. First, save the code above in a file called age_in_days.rb and place this in your
desktop or your project folder. Now, when you open up your terminal or console, navigate to this folder and type irb in
the command line. There, you can load the file and call the method by typing it. Here’s an example below.
/Documents/Ruby/my_code_folder >
/Documents/Ruby/my_code_folder > irb
>> load 'age_in_days.rb'
=> true
>> years_to_days_old
How old are you in years?
Now that you have a basic understanding of methods, see if you can write one yourself. You could write an adventure
word game or create your own calculator. The best way to get started is to just experiment!
33. Practice
1) What is the name of the method below?
def multiply(num1,num2)
num1 * num2
end
2) How many arguments does this method have?
def meeting(place, time, day)
...
end
3) What does this method return when called? (What's its output?)
def calculus
numbers = (25 * 37) / 42
numbers / 12 * 25
"Programming is not math"
end
4) Write a method that takes a word as an argument. Make the method return the word and the string " is awesome!" .
34. The Enumerable module is a collection of built-in Ruby methods that allow you to scan, sort, search and manipulate
collections. Remember that collections come in two forms, hashes and arrays. We’ll cover four of the basic enumerables
in this chapter:
each
each_with_index
select
map
Enumerables
35. You can think of the each method as one that operates a block, or a specific piece of code, onto each element in your
collection. For example, if we had a collection of toys we might store these in an array. If we wanted to print each toy on
the screen, we can call the each method. In the example below, we create the toys array with our collection of toys, then
we call each specific toy individually.
toys = [
"car",
"ball",
"action figure",
"stuffed animal"
]
toys.each { |toy| puts toy }
# Now each toy will be put to the screen:
car
ball
action figure
stuffed animal
Let’s dig into the each method to see what we did. Since this method belongs to the Array class, we can call it on our toys
array. We then give our each method a block of code to be executed or carried out and performed. In this case, we are
using the puts method. In our |pipes| we define a temporary variable toy and call the puts method on each toy that is
passed to our block.
Our each method knows to look at each element (our four toys) inside the array. This is called iterating over the array.
(Iterating over the array is just a fancy way of saying look at each toy in the collection). Now we store the value of each
array element inside our |pipes| and call the puts method on each element. We could have written the same code like so:
toys.each do |toy|
puts toy
end
The curly brackets are a way of writing do and end in one line. You don’t have to use them, but it is a shortcut that you
can use if you want! Either way works, and Ruby will look to execute the code inside of our do end or { } block. Now,
let’s look at how we might use the each method on a hash.
Imagine we had more than one toy in our collection. (If your parents are teaching you how to code in Ruby, you probably
have a lot more than one toy in your collection. Lucky you!) We might use a hash to better represent or organize our toy
box. Using each, we can print the toy and the number of toys in our collection.
toys = {"car" => 1, "ball" => 3, "action figure" => 2,
"stuffed animal" => 8}
toys.each { |key, value| puts "#{key} => #{value}" }
car => 1
ball => 3
action figure => 2
stuffed animal => 8
When using the each method on a hash, Ruby knows that each element in the array has a key and a value. We could
have used anything in our |pipes| to name our key and value pairs ( such as |x, y| ), but it’s easier to read when we
identify our key and value by their names. We then call the puts method again on each element, use our friend
interpolation #{ } to place our variable values in our string, and finally put the string of the toy, and number of toys, to the
screen.
Each
36. This enumerable method works much like each, except that it captures the index of the specific array its called on as well.
Remember that an array is an ordered collection that uses an index (sorting system) to organize the data or information in
the array. An array with five items has five indexes, from 0 to 4, and each index notes the location of each element.
my_array = ['ball', 'bat', 'hat']
my_array[2]
=> hat
my_array[0]
=> ball
In the example above, each item in the my_array can be called by its index. The ball is located at index 0, the bat at index
1, and our hat at index 2. If we only want to print every other item, we might use the each_with_index method like this:
my_array = ['ball', 'bat', 'hat', 'uniform', 'shoes']
my_array.each_with_index do |item, index|
if index % 2 == 0
puts item
end
end
Remember that a modulo is a way of looking at the remainder (left over part) of a number. So here, we put the item to the
screen if the index of the item has a remainder of zero when divided by 2. Since the indexes 0, 2, and 4 give no
remainder when divided by 2, we only call the puts method on items at these particular indexes.
We could use the even? method and curly braces to simplify our enumerable method.
my_array.each_with_index do |item, index|
puts item if index.even?
end
ball #item at index 0
hat #item at index 2
shoes #item at index 4
Ruby's even? method allows us to skip the modulo part altogether. Even? will return true if the number it is called upon is
an even number. Here is a way to see how the computer executes (carries out) each step in the each_with_index
method.
my_array = ['ball', 'bat', 'hat', 'uniform', 'shoes']
my_array.each_with_index do |item, index|
puts item if index.even?
end
|'ball', 0| if 0 is even?, then puts 'ball'
true => puts 'ball'
|'bat', 1| if 1 is even?, then puts 'bat'
false
|'hat', 2| if 2 is even?, then puts 'hat'
true => puts 'hat'
|'uniform', 3| if 3 is even?, then puts 'uniform'
false
|'shoes', 4| if 4 is even?, then puts 'shoes'
true => puts 'shoes'
The method starts out with an item and its index from the array. It then performs the block of code we specified between
Each_with_index
37. the do and end wrappers. In this example it will only put the name of the item if the index is an even number. Otherwise,
the if statement will return false and Ruby will not put anything to the screen for that particular block of code.
38. Okay, that might have been a little complicated to understand, but trust us, it will get easier with a little practice. Let’s look
at the select method to see how it iterates (looks over the stuff) in a collection. Select works by looking at the block of code
passed in, and then only returns the element if the block evaluates to be true.
$ [1,2,3,4].select { false }
=> []
$ [1,2,3,4].select { true }
=> [1, 2, 3, 4]
In the above example, the select method looks at each element in the array (1,2,3 and 4) and returns that element if our
block of code is true. Since our block of code is the false boolean, the select method does not evaluate to true and returns
nothing but an empty array. In the next line we pass true to the block and the select method returns every item in the
array.
Here’s an example of how we might use the select method in a more useful way. Imagine you have a collection of test
scores and you want to select only those scores above 80 points.
test_scores = [23,80,34,99,54,82,95,78,85]
test_scores.select do |score|
score > 80
end
=> [99, 82, 95, 85]
Here we use select to look at each element in the array. This value will be temporarily stored in the score variable. Then
each particular score is checked to see if it is greater than 80. Each of the scores that are greater than 80 will be collected
and returned as an array.
test_results = {
"Bobby" => 80, "Jane" => 95,
"Adam" => 99, "Doug" => 65,
"Sue" => 89, "Kim" => 91
}
good_students = test_results.select do |student, score|
score > 80
end
Here we have a test_results hash that contains a student’s name and their test score. We can use the select method to
grab each student and their score, for every student that scored higher than 80 points. If we were to run this, our
good_students hash would look like this:
$ good_students
=> {"Jane"=>95, "Adam"=>99, "Sue"=>89, "Kim"=>91}
You can imagine a program that runs simple select methods for hundreds of students in many classes in order to group
students by their grades. Ruby is useful for sorting, counting, classifying and organizing data. It would take a person
many hours to organize hundreds of students by grade and name, but a good program can do it almost instantly!
Select
39. Last but not least, let’s check out the map method. So far we’ve seen how different methods affect elements from our
collections. With map, we can select certain elements and modify them at the same time. Let’s jump into an example.
["dog", "cat", "snake", "mouse"].map do |animal|
animal.capitalize
end
=> ["Dog", "Cat", "Snake", "Mouse"]
Here we have an array of animals. We decide we want to capitalize each animal name. So we call map on the array and
another built in Ruby method, capitalize , on each item in the array. The capitalize method takes a string and makes its
first letter capitalized.
Map essentially finds and manipulates the data in the array, or maps your block of code to each specific element in that
array. To permanently alter an array with the map feature in Ruby, simply add the exclamation point to modify the existing
array.
animals = ["dog","cat","snake","mouse"]
animals.map! { |animal| animal.capitalize }
=> ["Dog", "Cat", "Snake", "Mouse"]
animals
=> ["Dog", "Cat", "Snake", "Mouse"]
At this point you understand two fundamental collections in programming languages: arrays and hashes. After diving into
the Enumerable module we revealed four of the most common methods used on these collections; each,
each_with_index, select and map. Now it’s time to test your knowledge with a few more examples.
Map
40. Practice
1) What numbers will the following code output?
[1,2,3,4,5].each { |num| puts num if num.odd? }
2) What would this each method output from this string?
"ThisdmakesdmoredsensedwithoutdD's".split("d").each {
|word| puts word
}
Note: We are method chaining in the above example. The string is being split into smaller separate strings at the
parameter passed in. Then the each method is called on that array.
3) What does select do for this hash?
food = {
"apple" => "fruit",
"carrot" => "vegetable",
"tomato" => "fruit"
}
food.select do |item, category|
category == "vegetable"
end
4) What will map do?
numbers = [1,2,3,4,5]
numbers.map { |num| num * 5 }
5) Now what is the value of numbers?
41. Understanding the In’s and Out’s
So far we’ve learned a lot about the basics of programming in Ruby. We’ve learned about strings, numbers, variables,
collections and methods--core concepts to all programming languages. These are the building blocks to programming.
Understanding these basics will help you with Ruby and any other languages you may learn in the future.
But there is one more aspect we should cover so you can start writing your own programs. So far we have modified
strings and numbers with input and output from our console. But what if we wanted to manipulate entire files instead?
We can start interacting with files using Ruby’s File Class. Here’s what it would look like to create, open and write to a file.
the_file = File.open("my_file.txt", "w")
the_file.puts "First line of our file."
the_file.close
In the example above, we used the File class and the open method, sending in two parameters. The first, my_file.txt is
the name of our file we are creating. The second is the w option, which tells Ruby we want to write to our file. On our next
line we use puts to write a string of text to our file. Lastly, we close the file with the close method.
If you open up a terminal window and enter Ruby’s Interactive Shell (IRB), you can run each of the lines of code above.
To see your file, type exit to leave the Ruby shell and type ls to list your files. You should see my_file.txt in your
directory. Type open my_file.txt , to open your file and see the line we wrote earlier with the puts statement.
If we want to add to this file, we could use the same code above, but with the append 'a' parameter passed in as the
second argument to open. If we used w , we would overwrite all of the contents of our file. If we use the 'a' parameter we
can add to our file without overwriting it.
Now, if we wanted to read our file, there are two basic ways for us to do that. We could either read all of the lines of the file
at once, or one at a time. Here’s how to read the file using the 'r' option. The 'r' option stands for read only.
file = File.open("our_file.txt", "r")
entire_file = file.read
puts entire_file
> This is a text file.
> This is line 2 of the file.
> And this is line 3.
=> nil
By using the 'r' option we are opening the file in read-only mode. Any writing we tried to do to our file here would fail. But
we can call the read method and store the contents of our file in the entire_file variable, and then put the variable to the
screen.
If we want to read each line, we can use the readlines method.
File.open("our_file.txt").readlines.each do |line|
puts line
end
Though both ways of reading the file will read and output each line, there is a significant difference in what these two
methods return. For our read method, the entire file is captured and nil is returned. For the readlines method, each line is
stored inside of an array, with the entire array returned at the end of the method.
Here’s an example of what that might look like.
Files
42. file_array = File.open("our_file.txt").readlines
=> ["This is our text file.n",
"This is line 2 of the file.n",
"And this is line 3."]
We open our file with File.open and then call the readlines method. Each line of the file is added to an array until all lines
have been read. Notice the n new line characters inside of our strings of text. Remember, we can remove these using
the each method and passing in a block with chomp.
file_array = File.open("our_file.txt").readlines
.each { |line| line.chomp! }
=> ["This is our text file.",
"This is line 2 of the file.",
"And this is line 3."]
Wow! Now you know how to open, write, and read files! And don’t forget to close your files in your programs with the
close method. It can be a bad thing to leave them open, because the computer won’t actually write and save the file until
just before its closed. Also, open files can lead to overloading your memory usage.
43. You’ve just finished the first book ever for Ruby for kids. Now, move to Silicon Valley and ask your parents for some seed
funding. Soon you will have raised a Series A round and have a large equity stake in your very own tech startup! In no
time, you will be able to give your parents an allowance.
In all seriousness, one of the beauties of programming is that there is always more to learn. You have crossed one of the
most difficult hurdles by simply finishing this book, but this is only the tip of the ice berg. Check out the many resources
online to learn more about Ruby and other great languages, go through some tutorials, start building things and hone
your craft.
Happy hacking!
Congratulations!
44. Chapter 2 - Numbers
1) 2 + 3 + 5 => 10
2) 10 - 3 => 7
3) 9 / 3 => 3
4) 4 * 2 => 8
5) 4 ** 2 => 16
6) What is the result of 11 % 5 ? => 1
5 goes into 11 only twice, for a total of 10. 11 minus 10 leaves a remainder of 1
7) What is 14 % 3 ? => 2
8) A wizard carries two numbers (one even and one odd) in each hand. He won't open his hands to show you, but he will
let you use modulo. Your task is to find out which hand holds an even number, and which holds the odd.
If we mark each number as "X" we can use modulo: if x % 2 == 0 is true , it’s an even number. if x % 2 == 0 is false , it’s
an odd number.
Chapter 3 - Strings
1) puts "What is the result" + " of " + "this operation?" What is the return result of this operation? => nil
The above puts method concatenated the strings, putting the result to the screen and returning nil.
2) "This string minus" - "That string"
NoMethodError: undefined method `-' for
"This string minus":String
There is no '-' method for Strings, so the operation cannot be done. Remember, - is for numbers!
3) "1234.55".to_i => 1234
4) "1234.55".to_f => 1234.55
5) "Not a number".to_i => 0
6) puts "1n2n3n"
1
2
3
=> nil
7) Why might it be useful that the 'to integer' (to_i) method return zero on strings that can’t be represented as numbers?
"to_i" can still be called on a string without numbers, and so it returns a zero, noting the successful call (no error) and the
value zero, which could represent zero numbers in the string.
Answers to Practice Problems
45. 8) What do you think the length method does? "Count".length => 5 Counts the number of letters or items in the string.
9) How about the split method? "Count".split("") => ["C", "o", "u", "n", "t"]
Calling the 'split' method with no space ("") as the argument causes the string to be split at each character and placed
inside of an array.
10) What do you think slice does? "Count".slice(2) => "u"
Slice grabs the character from the index argument passed in, which in this case is an index of 2. The letter "u" is at index
2 in our string "Count". string: ["C", "o", "u", "n", "t"] indexes: [ 0 , 1 , 2 , 3 , 4 ]
Chapter 4 - Variables
1) Store the value of 54 / 3 into the variable x. What is the value of x? x = 54 / 3 => 18
2) Give the value of x (from problem 1) to y, a new variable. Now make x equal to itself divided by 3. What’s the value of
x? What’s the value of y?
y = x
=> 18 # y is assigned the x value, 18
x = x / 3 # or written as x /= 3
=> 6 # x is now the value of 18 / 3
3) What if we performed some math on our variables? If we set x to 12, what’s x divided by 3?
x = 12
x / 3
=> 4
4) What’s the value of x now? => 12 When we divided X by 3, we didn't store the result, so X's value does not change
since it was assigned 12.
Chapter 5 - If and Else
1) Is 3 > 5 ? => false
2) 3 < 5 => true
3) 5 == 5 => true
4) 10 >= 10 => true
5) 10 <= 12 => true
6) 10 != 10 => false
7) 10.object_id == 10.object_id => true
What about strings? 8) "dog" == "cat" => false
9) "cat" == "cat" => true
10)
46. "cat".object_id == "cat".object_id
=> false
# Numbers have object id's that don't change.
Everytime a string is created, however, a new object_id is created for that string.
Chapter 6 - Loops
1) What’s the current value of the time variable? => 8
Even though our last value outputted was 7, the next code block (current_time = current_time + 1) is executed, and so our
variable increments by 1 to equal 8.
Chapter 7 - Collections
1) Create a hash for the Wizard’s magic bag. Inside the bag, we’ll put 3 frogs, 5 herbs, and 10 scrolls. Assign the hash to
the variable "bag". What does your hash look like?
bag = {
"frogs" => 3,
"herbs" => 5,
"scrolls" => 10
}
2) Remember, hashes consist of key value pairs of any data, not just numbers. Let’s add a wizard’s spell and its result
(which the wizard can never seem to remember). Add a spell to our wizard’s bag with the key: "shazam" and the value
"turns subject into a frog". Now what's in our bag?
bag["shazam"] = "turns subject into a frog"
bag
=> {"frogs" => 3,
"herbs" => 5,
"scrolls" => 10,
"shazam" => "turns subject into a frog"}
3) Our wizard has a change of heart and decides he never wants to turn anyone into a frog. How can we remove the spell
"shazam" from our wizard bag?
bag.delete("shazam")
=> "turns subject into a frog"
4) Our wizard has recently acquired 3 different types of potions. 4 orange potions, 5 blue potions and 7 red potions. How
might we add another hash of potions to our bag? Hint: remember that we can have collections within a collection.
47. bag["potions"] = {
"orange" => 4,
"blue" => 5,
"red" => 10
}
bag
=> { "frogs"=>3, "herbs"=>5,
"scrolls"=>10,
"potions"=> {
"orange"=>3,
"blue"=>5,
"red"=>10
}
}
5) Now that our bag has four keys (frogs, herbs, scrolls and potions), we can use these keys to access our data. In order
to make a new spell, our wizard needs 2 frogs, 3 herbs, 1 scroll and 2 blue potions. How can we remove these items from
our hash? Hint: We can set the value of a key item to itself, minus how many items removed.
bag["frogs"] = bag["frogs"] - 2
=> 1
bag["herbs"] = bag["herbs"] - 3
=> 2
bag["scrolls"] = bag["scrolls"] - 1
=> 9
bag["potions"]["blue"] = bag["potions"]["blue"] - 2
=> 3
bag
=> {
"frogs" => 1,
"herbs" => 2,
"scrolls" => 9,
"potions" => {
"orange" => 4,
"blue" => 3,
"red" => 10
}
}
Chapter 8 - Methods
1) What is the name of the method below?
def multiply(num1,num2)
num1 * num2
end
=> multiply
2) How many arguments does this method have?
def meeting(place, time, day)
...
end
=> 3
3) What does this method return when called? (What's its output?)
48. def calculus
numbers = (25 * 37) / 42
numbers / 12 * 25
"Programming is not math"
end
=> "Programming is not math"
Ruby methods return their last line by default
4) Write a method that takes a word as an argument. Make the method return the word and the string "is awesome!".
def awesomify(word)
word + " is awesome!"
end
Chapter 9 - Enumerables
1) What numbers will the following code output?
[1,2,3,4,5].each { |num| puts num if num.odd? }
1
3
5
=> [1, 2, 3, 4, 5]
2) What would this each method output from this string?
"ThisdmakesdmoredsensedwithoutdD's".split("d").each {
|word| puts word
}
This
makes
more
sense
without
D's
=> ["This", "makes", "more", "sense", "without", "D's"]
3) What does select do for this hash?
food = {
"apple" => "fruit",
"carrot" => "vegetable",
"tomato" => "fruit"
}
food.select do |item, category|
category == "vegetable"
end
=> {"carrot"=>"vegetable"}
4) What will map do?
numbers = [1,2,3,4,5]
numbers.map { |num| num * 5 }
=> [5, 10, 15, 20, 25]
5) Now what is the value of numbers?
50. If you would like to contact me with any feedback or questions, you can find me on the web in various places using:
mrdougwright
Twitter => @mrdougwright
Email => mrdougwright@gmail.com
Blog => dogwithrug.com
Contact