Working with Numbers

In order to do these exercises you should have read at least the chapter about [built_in_classes/numbers.html].

Exercise 1.1

In irb, calcluate:

To start irb open your terminal and type irb, then hit the return key (enter). To quit it (and get back to your system shell prompt) type exit or press ctrl-d.

Exercise 1.2

What do you think happens when you combine floats and integers the following in the following calculations?

Try computing these in irb:

Is the result a float or an integer?

Exercise 1.3

Try finding out what “modulo” means by asking Google.

In Ruby (and many other languages) the operator for modulo is %.

Try the following in irb:

And:

Exercise 1.4

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 -99.

Exercise 1.5

In 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.

Show solution