Generate Random Number in Ruby

Sometimes we would also need to generate x random numbers from n to m

1
x.times.map{n + Random.rand( m - n )}
1
2
3
Random.new.rand(n...m)
#in ruby 1.9.3
Random.rand(n...m)

if you only want to select a random item form array.

1
2
%(a b c d e).sample
(n...m).to_a.sample

Some other ways by using SecureRandom

1
2
3
4
5
6
7
8
9
require 'securerandom'

p SecureRandom.random_number(100) #=> 15
p SecureRandom.random_number(100) #=> 88

p SecureRandom.random_number #=> 0.596506046187744
p SecureRandom.random_number #=> 0.350621695741409

p SecureRandom.hex #=> "eb693ec8252cd630102fd0d0fb7c3485"
Comments

Comments