[ruby-on-rails] How to get a random number in Ruby

How do I generate a random number between 0 and n?

The answer is


Don't forget to seed the RNG with srand() first.


Easy way to get random number in ruby is,

def random    
  (1..10).to_a.sample.to_s
end

Simplest answer to the question:

rand(0..n)

rand(6)    #=> gives a random number between 0 and 6 inclusively 
rand(1..6) #=> gives a random number between 1 and 6 inclusively

Note that the range option is only available in newer(1.9+ I believe) versions of ruby.


Try array#shuffle method for randomization

array = (1..10).to_a
array.shuffle.first

Don't forget to seed the RNG with srand() first.


You can generate a random number with the rand method. The argument passed to the rand method should be an integer or a range, and returns a corresponding random number within the range:

rand(9)       # this generates a number between 0 to 8
rand(0 .. 9)  # this generates a number between 0 to 9
rand(1 .. 50) # this generates a number between 1 to 50
#rand(m .. n) # m is the start of the number range, n is the end of number range

If you're not only seeking for a number but also hex or uuid it's worth mentioning that the SecureRandom module found its way from ActiveSupport to the ruby core in 1.9.2+. So without the need for a full blown framework:

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"

It's documented here: Ruby 1.9.3 - Module: SecureRandom (lib/securerandom.rb)


What about this?

n = 3
(0..n).to_a.sample

Well, I figured it out. Apparently there is a builtin (?) function called rand:

rand(n + 1)

If someone answers with a more detailed answer, I'll mark that as the correct answer.


While you can use rand(42-10) + 10 to get a random number between 10 and 42 (where 10 is inclusive and 42 exclusive), there's a better way since Ruby 1.9.3, where you are able to call:

rand(10...42) # => 13

Available for all versions of Ruby by requiring my backports gem.

Ruby 1.9.2 also introduced the Random class so you can create your own random number generator objects and has a nice API:

r = Random.new
r.rand(10...42) # => 22
r.bytes(3) # => "rnd"

The Random class itself acts as a random generator, so you call directly:

Random.rand(10...42) # => same as rand(10...42)

Notes on Random.new

In most cases, the simplest is to use rand or Random.rand. Creating a new random generator each time you want a random number is a really bad idea. If you do this, you will get the random properties of the initial seeding algorithm which are atrocious compared to the properties of the random generator itself.

If you use Random.new, you should thus call it as rarely as possible, for example once as MyApp::Random = Random.new and use it everywhere else.

The cases where Random.new is helpful are the following:

  • you are writing a gem and don't want to interfere with the sequence of rand/Random.rand that the main programs might be relying on
  • you want separate reproducible sequences of random numbers (say one per thread)
  • you want to be able to save and resume a reproducible sequence of random numbers (easy as Random objects can marshalled)

This link is going to be helpful regarding this;

http://ruby-doc.org/core-1.9.3/Random.html

And some more clarity below over the random numbers in ruby;

Generate an integer from 0 to 10

puts (rand() * 10).to_i

Generate a number from 0 to 10 In a more readable way

puts rand(10)

Generate a number from 10 to 15 Including 15

puts rand(10..15)

Non-Random Random Numbers

Generate the same sequence of numbers every time the program is run

srand(5)

Generate 10 random numbers

puts (0..10).map{rand(0..10)}

you can do rand(range)

x = rand(1..5)

While you can use rand(42-10) + 10 to get a random number between 10 and 42 (where 10 is inclusive and 42 exclusive), there's a better way since Ruby 1.9.3, where you are able to call:

rand(10...42) # => 13

Available for all versions of Ruby by requiring my backports gem.

Ruby 1.9.2 also introduced the Random class so you can create your own random number generator objects and has a nice API:

r = Random.new
r.rand(10...42) # => 22
r.bytes(3) # => "rnd"

The Random class itself acts as a random generator, so you call directly:

Random.rand(10...42) # => same as rand(10...42)

Notes on Random.new

In most cases, the simplest is to use rand or Random.rand. Creating a new random generator each time you want a random number is a really bad idea. If you do this, you will get the random properties of the initial seeding algorithm which are atrocious compared to the properties of the random generator itself.

If you use Random.new, you should thus call it as rarely as possible, for example once as MyApp::Random = Random.new and use it everywhere else.

The cases where Random.new is helpful are the following:

  • you are writing a gem and don't want to interfere with the sequence of rand/Random.rand that the main programs might be relying on
  • you want separate reproducible sequences of random numbers (say one per thread)
  • you want to be able to save and resume a reproducible sequence of random numbers (easy as Random objects can marshalled)

you can do rand(range)

x = rand(1..5)

How about this one?

num = Random.new
num.rand(1..n)

What about this?

n = 3
(0..n).to_a.sample

Well, I figured it out. Apparently there is a builtin (?) function called rand:

rand(n + 1)

If someone answers with a more detailed answer, I'll mark that as the correct answer.


This link is going to be helpful regarding this;

http://ruby-doc.org/core-1.9.3/Random.html

And some more clarity below over the random numbers in ruby;

Generate an integer from 0 to 10

puts (rand() * 10).to_i

Generate a number from 0 to 10 In a more readable way

puts rand(10)

Generate a number from 10 to 15 Including 15

puts rand(10..15)

Non-Random Random Numbers

Generate the same sequence of numbers every time the program is run

srand(5)

Generate 10 random numbers

puts (0..10).map{rand(0..10)}

You can simply use random_number.

If a positive integer is given as n, random_number returns an integer: 0 <= random_number < n.

Use it like this:

any_number = SecureRandom.random_number(100) 

The output will be any number between 0 and 100.


Maybe it help you. I use this in my app

https://github.com/rubyworks/facets
class String

  # Create a random String of given length, using given character set
  #
  # Character set is an Array which can contain Ranges, Arrays, Characters
  #
  # Examples
  #
  #     String.random
  #     => "D9DxFIaqR3dr8Ct1AfmFxHxqGsmA4Oz3"
  #
  #     String.random(10)
  #     => "t8BIna341S"
  #
  #     String.random(10, ['a'..'z'])
  #     => "nstpvixfri"
  #
  #     String.random(10, ['0'..'9'] )
  #     => "0982541042"
  #
  #     String.random(10, ['0'..'9','A'..'F'] )
  #     => "3EBF48AD3D"
  #
  #     BASE64_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", '_', '-']
  #     String.random(10, BASE64_CHAR_SET)
  #     => "xM_1t3qcNn"
  #
  #     SPECIAL_CHARS = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+", "|", "/", "?", ".", ",", ";", ":", "~", "`", "[", "]", "{", "}", "<", ">"]
  #     BASE91_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", SPECIAL_CHARS]
  #     String.random(10, BASE91_CHAR_SET)
  #      => "S(Z]z,J{v;"
  #
  # CREDIT: Tilo Sloboda
  #
  # SEE: https://gist.github.com/tilo/3ee8d94871d30416feba
  #
  # TODO: Move to random.rb in standard library?

  def self.random(len=32, character_set = ["A".."Z", "a".."z", "0".."9"])
    chars = character_set.map{|x| x.is_a?(Range) ? x.to_a : x }.flatten
    Array.new(len){ chars.sample }.join
  end

end

https://github.com/rubyworks/facets/blob/5569b03b4c6fd25897444a266ffe25872284be2b/lib/core/facets/string/random.rb

It works fine for me


Well, I figured it out. Apparently there is a builtin (?) function called rand:

rand(n + 1)

If someone answers with a more detailed answer, I'll mark that as the correct answer.


How about this one?

num = Random.new
num.rand(1..n)

Well, I figured it out. Apparently there is a builtin (?) function called rand:

rand(n + 1)

If someone answers with a more detailed answer, I'll mark that as the correct answer.


You can simply use random_number.

If a positive integer is given as n, random_number returns an integer: 0 <= random_number < n.

Use it like this:

any_number = SecureRandom.random_number(100) 

The output will be any number between 0 and 100.


If you're not only seeking for a number but also hex or uuid it's worth mentioning that the SecureRandom module found its way from ActiveSupport to the ruby core in 1.9.2+. So without the need for a full blown framework:

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"

It's documented here: Ruby 1.9.3 - Module: SecureRandom (lib/securerandom.rb)


range = 10..50

rand(range)

or

range.to_a.sample

or

range.to_a.shuffle(this will shuffle whole array and you can pick a random number by first or last or any from this array to pick random one)


Maybe it help you. I use this in my app

https://github.com/rubyworks/facets
class String

  # Create a random String of given length, using given character set
  #
  # Character set is an Array which can contain Ranges, Arrays, Characters
  #
  # Examples
  #
  #     String.random
  #     => "D9DxFIaqR3dr8Ct1AfmFxHxqGsmA4Oz3"
  #
  #     String.random(10)
  #     => "t8BIna341S"
  #
  #     String.random(10, ['a'..'z'])
  #     => "nstpvixfri"
  #
  #     String.random(10, ['0'..'9'] )
  #     => "0982541042"
  #
  #     String.random(10, ['0'..'9','A'..'F'] )
  #     => "3EBF48AD3D"
  #
  #     BASE64_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", '_', '-']
  #     String.random(10, BASE64_CHAR_SET)
  #     => "xM_1t3qcNn"
  #
  #     SPECIAL_CHARS = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+", "|", "/", "?", ".", ",", ";", ":", "~", "`", "[", "]", "{", "}", "<", ">"]
  #     BASE91_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", SPECIAL_CHARS]
  #     String.random(10, BASE91_CHAR_SET)
  #      => "S(Z]z,J{v;"
  #
  # CREDIT: Tilo Sloboda
  #
  # SEE: https://gist.github.com/tilo/3ee8d94871d30416feba
  #
  # TODO: Move to random.rb in standard library?

  def self.random(len=32, character_set = ["A".."Z", "a".."z", "0".."9"])
    chars = character_set.map{|x| x.is_a?(Range) ? x.to_a : x }.flatten
    Array.new(len){ chars.sample }.join
  end

end

https://github.com/rubyworks/facets/blob/5569b03b4c6fd25897444a266ffe25872284be2b/lib/core/facets/string/random.rb

It works fine for me


Try array#shuffle method for randomization

array = (1..10).to_a
array.shuffle.first

range = 10..50

rand(range)

or

range.to_a.sample

or

range.to_a.shuffle(this will shuffle whole array and you can pick a random number by first or last or any from this array to pick random one)


Easy way to get random number in ruby is,

def random    
  (1..10).to_a.sample.to_s
end

Simplest answer to the question:

rand(0..n)

Don't forget to seed the RNG with srand() first.


rand(6)    #=> gives a random number between 0 and 6 inclusively 
rand(1..6) #=> gives a random number between 1 and 6 inclusively

Note that the range option is only available in newer(1.9+ I believe) versions of ruby.


Examples related to ruby-on-rails

Embed ruby within URL : Middleman Blog Titlecase all entries into a form_for text field Where do I put a single filter that filters methods in two controllers in Rails Empty brackets '[]' appearing when using .where How to integrate Dart into a Rails app Rails 2.3.4 Persisting Model on Validation Failure How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? Rails: Can't verify CSRF token authenticity when making a POST request Uncaught ReferenceError: React is not defined

Examples related to ruby

Uninitialized Constant MessagesController Embed ruby within URL : Middleman Blog Titlecase all entries into a form_for text field Ruby - ignore "exit" in code Empty brackets '[]' appearing when using .where find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException) How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite? How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? How to update Ruby with Homebrew?

Examples related to ruby-on-rails-3

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? rake assets:precompile RAILS_ENV=production not working as required How do you manually execute SQL commands in Ruby On Rails using NuoDB Check if record exists from controller in Rails How to restart a rails server on Heroku? How to have a drop down <select> field in a rails form? "Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application Adding a simple spacer to twitter bootstrap How can I change cols of textarea in twitter-bootstrap? Rails: FATAL - Peer authentication failed for user (PG::Error)

Examples related to ruby-on-rails-4

Uninitialized Constant MessagesController Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? NameError: uninitialized constant (rails) How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1) ActionController::UnknownFormat Add a reference column migration in Rails 4 PG::ConnectionBad - could not connect to server: Connection refused Auto-loading lib files in Rails 4 cannot load such file -- bundler/setup (LoadError) Rails 4: how to use $(document).ready() with turbo-links

Examples related to random

How can I get a random number in Kotlin? scikit-learn random state in splitting dataset Random number between 0 and 1 in python In python, what is the difference between random.uniform() and random.random()? Generate random colors (RGB) Random state (Pseudo-random number) in Scikit learn How does one generate a random number in Apple's Swift language? How to generate a random string of a fixed length in Go? Generate 'n' unique random numbers within a range What does random.sample() method in python do?