generate a random number in ruby

To generate a random number in Ruby, you can use the rand method.

main.rb
# To generate a random integer between 0 and 9
random_number = rand(10)

# To generate a random float between 0 and 1
random_float = rand
138 chars
6 lines

The rand method can also accept an argument to specify a range of numbers. For example:

main.rb
# To generate a random integer between 1 and 6 (inclusive)
dice_roll = rand(1..6)

# To generate a random float between -5 and 5
random_number = rand(-5.0..5.0)
161 chars
6 lines

Keep in mind that rand generates a pseudorandom number, which means that the sequence of numbers may not be truly random, but they'll appear random enough for most practical purposes.

gistlibby LogSnag