Working with Numbers
In order to do these exercises you should have read at least the chapter about [built_in_classes/numbers.html].
- How many hours are in a year.
- How many minutes are in a decade?
- How many seconds old are you?
irb open your terminal and type
return key (
enter). To quit it (and get back
to your system shell prompt) type
exit or press
What do you think happens when you combine floats and integers the following in the following calculations?
Try computing these in
3 / 2
3.0 / 2
3 / 2.0
4 * 2.0
0 + 1
Is the result a float or an integer?
Try finding out what “modulo” means by asking Google.
In Ruby (and many other languages) the operator for modulo is
Try the following in
5 % 2
15 % 2
505 % 2
8 % 5
9 % 5
10 % 5
11 % 5
Methods are a way of “doing something with an object”, and you’ll learn a lot more about them in a few chapters.
In Ruby, numbers have methods that allow you to check whether the number is odd or even.
Look through the documentation for integer numbers and find the methods that tell if a number is odd or even.
Look at the examples for some of the other methods on that page.
You can use a method by appending a dot
. and then the method name
to the object. E.g.
-99.abs uses (we also say: “calls”) the method
abs on the number
irb, use these methods to find out if certain numbers are odd or even.
Try a bunch of numbers like
0, 1, 2, 99, -502 etc.
Try for yourself what it does, and google for “ruby number odd even” to find the documentation for these methods.