Cómo obtener un número aleatorio en Ruby
¿Cómo puedo generar un número aleatorio entre 0
y n
?
17 answers
Uso rand(range)
De Números aleatorios de Rubí :
Si necesita un entero aleatorio para simular un rollo de un dado de seis lados, usaría:
1 + rand(6)
. Un rollo en juego de dados podría ser simulado con2 + rand(6) + rand(6)
.Finalmente, si solo necesita un flotador aleatorio, simplemente llame a
rand
sin argumentos.
Como Marc-André Lafortune menciona en su respuesta a continuación (vota), Ruby 1.9.2 tiene su propia clase Random
(que el propio Marc-André ayudó a depurar, de ahí el destino 1.9.2 para esa característica).
Por ejemplo, en este juego donde necesitas adivinar 10 números, puedes inicializarlos con:
10.times.map{ 20 + Random.rand(11) }
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]
Nota:
Usar
Random.new.rand(20..30)
(usarRandom.new
) generalmente no sería una buena idea, como explicó en detalle (de nuevo) Marc-André Lafortune, en su respuesta (de nuevo).Pero si no usas
Random.new
, entonces el método de claserand
solo toma un valormax
, no unRange
, como banister (energéticamente) señala en el comentario (y como se documenta en los documentos paraRandom
). Solo el método de instancia puede tomar unRange
, como se ilustra en generar un número aleatorio con 7 dígitos.
Esta es la razón por la que el equivalente de Random.new.rand(20..30)
sería 20 + Random.rand(11)
, ya que Random.rand(int)
devuelve " un entero aleatorio mayor o igual a cero y menor que el argumento."20..30
incluye 30, necesito llegar a un número aleatorio entre 0 y 11, excluyendo 11.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-06 14:35:56
Mientras que puedes usar rand(42-10) + 10
para obtener un número aleatorio entre 10
y 42
(donde 10 es inclusivo y 42 exclusivo), hay una mejor manera desde Ruby 1.9.3, donde puedes llamar:
rand(10...42) # => 13
Disponible para todas las versiones de Rubybackports
gem.
Ruby 1.9.2 también introdujo la clase Random
para que pueda crear sus propios objetos generadores de números aleatorios y tiene una API agradable:
r = Random.new
r.rand(10...42) # => 22
r.bytes(3) # => "rnd"
La propia clase Random
actúa como un generador aleatorio, por lo que llame directamente:
Random.rand(10...42) # => same as rand(10...42)
Notas sobre el Random.new
En la mayoría de los casos, lo más simple es usar rand
o Random.rand
. Crear un nuevo generador aleatorio cada vez que quieras un número aleatorio es una muy mala idea. Si hace esto, obtendrá las propiedades aleatorias del algoritmo de siembra inicial que son atroces en comparación con las propiedades del propio generador aleatorio .
Si utiliza Random.new
, por lo tanto, debe llamarlo tan raramente como posible , por ejemplo una vez como MyApp::Random = Random.new
y usarlo en cualquier otro lugar.
Los casos en los que Random.new
es útil son los siguientes: {[19]]}
- usted está escribiendo una gema y no quiere interferir con la secuencia de
rand
/Random.rand
que los programas principales podrían confiar en - quieres secuencias reproducibles separadas de números aleatorios (digamos uno por hilo)
- desea poder guardar y reanudar una secuencia reproducible de números aleatorios (tan fácil como los objetos
Random
pueden marshalled)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-12 17:38:27
Si no solo estás buscando un número, sino también hex o uuid, vale la pena mencionar que el módulo SecureRandom
encontró su camino desde ActiveSupport
hasta el núcleo ruby en 1.9.2+. Así que sin la necesidad de un marco completo:
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"
Está documentado aquí: Ruby 1.9.3 - Module: SecureRandom (lib/securerandom.rb)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-08 08:42:19
Puede generar un número aleatorio con el método rand
. El argumento pasado al método rand
debe ser un integer
o un range
, y devuelve un número aleatorio correspondiente dentro del rango:
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-21 00:54:21
Bueno, lo descubrí. Al parecer hay un builtin (?) función llamada rand:
rand(n + 1)
Si alguien responde con una respuesta más detallada, la marcaré como la respuesta correcta.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-13 18:10:10
¿Qué pasa con esto?
n = 3
(0..n).to_a.sample
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-23 06:02:22
La respuesta más simple a la pregunta:
rand(0..n)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-20 10:45:54
rand(6) #=> gives a random number between 0 and 6 inclusively
rand(1..6) #=> gives a random number between 1 and 6 inclusively
Tenga en cuenta que la opción range solo está disponible en versiones más recientes(creo que 1.9+) de ruby.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-15 23:31:45
Rango = 10..50
Rand (rango)
O
Range. to_a. sample
O
Range. to_a. shuffle (esto barajará toda la matriz y puede elegir un número aleatorio por primera o última o cualquiera de esta matriz para elegir uno aleatorio)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-29 10:32:32
Simplemente puede usar random_number
.
Si se da un entero positivo como n, random_number
devuelve un entero: 0 random_number
Úsalo así:
any_number = SecureRandom.random_number(100)
La salida será cualquier número entre 0 y 100.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-16 11:58:57
Este enlace va a ser útil con respecto a esto;
Http://ruby-doc.org/core-1.9.3/Random.html
Y un poco más de claridad a continuación sobre los números aleatorios en ruby;
Generar un entero de 0 a 10
puts (rand() * 10).to_i
Generar un número de 0 a 10 De una manera más legible
puts rand(10)
Generar un número de 10 a 15 Incluidos 15
puts rand(10..15)
Números aleatorios no aleatorios
Generar la misma secuencia de números cada tiempo el programa se ejecuta
srand(5)
Generar 10 números aleatorios
puts (0..10).map{rand(0..10)}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-24 17:38:49
Puedes hacer rand (rango)
x = rand(1..5)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-22 23:09:00
Try array#shuffle
método de aleatorización
array = (1..10).to_a
array.shuffle.first
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-23 18:15:29
Tal vez te ayude. Yo uso esto en mi aplicación
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
Funciona bien para mí
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-11 13:59:43
¿Qué tal este?
num = Random.new
num.rand(1..n)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-11 14:31:35
La manera fácil de obtener números aleatorios en ruby es,
def random
(1..10).to_a.sample.to_s
end
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-16 10:04:47
No olvides sembrar el RNG con srand() primero.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-13 18:15:52