2. Ruby Data Types and Operations
Activity 2.01: Dice Roller Program
Solution
- We begin by simulating the rolling of a dice. Ruby has an in-built
rand
method, which returns a random number. It takes an argument as an integer and returns a random number. Openirb
and type the following:rand 2
- Now, repeat that a few more times. You'll notice the numbers you get in response are either
0
or1
, never2
. This is what 0-indexing means: the first number is always zero. - The problem here is that a die never starts with zero, it starts with one. So, let's create a method for that.
- Open up
roller.rb
and add the following method to it:def roll rand(6) + 1 end puts roll
- Run that file a few times, and you'll see that we have successfully simulated rolling a dice.
- Next, roll a dice with any number of sides. Continue to expand on the previous program and add an argument to this method. Open
roller.rb
and add the following code:def roll(sides...