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

Get Learn to Program, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.