Creating Classes

We’ve now seen a smattering of different classes. However, it’s easy to come up with kinds of objects that Ruby doesn’t have—objects you’d like it to have. Fear not; creating a new class is as easy as extending an old one. Let’s say we wanted to make some dice in Ruby, for example. Here’s how we could make the Die class:

class​ Die
def​ roll
1 + rand(6)
end
end
# Let's make a couple of dice...
dice = [Die.new, Die.new]
# ...and roll them.
dice.each ​do​ |die|
puts die.roll
end
4
2

(If you skipped the section on random numbers, rand(6) just gives a random number between 0 and 5.) And that’s it! These are objects of our very own. Roll the dice a few times (run the program again), and watch what turns up.

We can define all sorts of methods for our objects…but there’s something missing. Working with these objects feels a lot like programming before we learned about variables. Look at our dice, for example. We can roll them, and each time we do they give us a different number. But if we wanted to hang onto that number, we would have to create a variable to point to the number. It seems like any decent die should be able to have a number and that rolling the die should change that number. If we keep track of the die, we shouldn’t also have to keep track of the number it is showing.

However, if we try to store the number we rolled in a (local) variable in roll, it will be gone as soon as roll is finished. We need to store the number in a different kind of variable, an instance variable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.206.43