Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKourosh Raeen
23,733 PointsRange of values returned by Random.new.rand(5)
In the first example, Jason Seifer seems to suggest that Random.new.rand(max) returns an integer between 0 and max, inclusive. However, the documentation reads "When max is an integer, rand returns a random integer greater or equal to zero and less than max". So Random.new.rand(5) will not return 5.
1 Answer
Todd MacIntyre
12,248 PointsCorrect. If you want a random number between 0 and 5, use this code:
number = Random.new.rand(5 + 1).floor
The floor method will round the float down to the nearest integer giving the range of 0-5. Hope this helps!
Kourosh Raeen
23,733 PointsKourosh Raeen
23,733 PointsThanks Todd! But there is no need for using floor. rand(6) already returns an integer between 0 and 5 inclusive.
Todd MacIntyre
12,248 PointsTodd MacIntyre
12,248 PointsYes, in the case of integers that will be the case. But if dealing with float randomization you will want the floor method or even the to_int method which truncates the float answer to an integer. Of course, this completely depends on what you're using for your max.