Skip to Main Content
Learn to Program, 2nd Edition
book

Learn to Program, 2nd Edition

by Chris Pine
March 2009
Intermediate to advanced content levelIntermediate to advanced
194 pages
4h
English
Pragmatic Bookshelf
Content preview from Learn to Program, 2nd Edition

Random Numbers

Ruby comes with a pretty nice random number generator. The method to get a randomly chosen number is rand. If you call rand just like that, you’ll get a float greater than or equal to 0.0 and less than 1.0. If you give it an integer parameter (by calling rand(5), for example), it will give you an integer greater than or equal to 0 and less than 5 (so five possible numbers, from 0 to 4).

Let’s see rand in action:

puts rand
puts rand
puts rand
puts(rand(100))
puts(rand(100))
puts(rand(100))
puts(rand(1))
puts(rand(1))
puts(rand(1))
puts(rand(9999999999999999999999999999999999999))
puts(​'The weatherman said there is a'​)
puts(rand(101).to_s + ​'% chance of rain,'​)
puts(​'but you can never trust a weatherman.'​)
0.780420251671991
0.27612531216364 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learn to Program, 3rd Edition

Learn to Program, 3rd Edition

Chris Pine
The Book of Ruby

The Book of Ruby

Huw Collingbourne

Publisher Resources

ISBN: 9781680500172Errata