How would express our dice algorithms in Ruby? The first one might
look like this.
1: class StandardDice
2: def toss
3: @top = rand(6) + 1
4: end
5: def top
6: @top
7: end
8: end
|
|
- [1] The class keyword introduces a class, a blueprint for creating objects.
- [2] Function definitions within a class are called methods. You can send the message toss to any object built from the class StandardDice.
- [3a] Variables that begin with an "@" character are attributes of the object. Each individual StandardDice object will get its own copy of @top.
- [3b] The rand(n) function returns a random number in the range 0 to (n-1). We need to add one to the result to get a random number between 1 and 6.
- [5-7] Attributes are private in Ruby. That means no one outside the class can read or modify the value of @top. To make the value of @top available, we must write a method to return the value. We choose to call our method top.
|