¿Cómo generar un número aleatorio entre a y b en Ruby?
Para generar un número aleatorio entre 3 y 10, por ejemplo, utilizo: rand(8) + 3
¿Hay una manera más agradable de hacer esto (algo así como rand(3, 10)
)?
8 answers
ACTUALIZACIÓN: Ruby 1.9.3 {[3] } también acepta rangos
rand(a..b)
Http://www.rubyinside.com/ruby-1-9-3-introduction-and-changes-5428.html
Convertir a matriz puede ser demasiado caro, y es innecesario.
(a..b).to_a.sample
O
[*a..b].sample
Estándar en Ruby 1.8.7+.
Nota: fue nombrado # choice en 1.8.7 y renombrado en versiones posteriores.
Pero de todos modos, la generación de matriz necesita recursos, y la solución que ya escrito es lo mejor que puedes hacer.
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-29 20:30:13
Random.new.rand(a..b)
Donde a
es su valor más bajo y b
es su valor más alto.
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-10-29 11:03:20
rand(3..10)
Cuando max es un Rango, rand devuelve un número aleatorio donde rango.miembro?(número) == true.
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-12-16 18:53:35
Solo tenga en cuenta la diferencia entre los operadores de rango:
3..10 # includes 10
3...10 # doesn't include 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
2015-09-03 11:45:40
Ver esta respuesta: existe en Ruby 1.9.2, pero no en versiones anteriores. Personalmente creo que rand ( 8) + 3 está bien, pero si estás interesado echa un vistazo a la clase Aleatoria descrita en el enlace.
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-05-23 11:47:21
Para 10 y 10 * * 24
rand(10**24-10)+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
2010-12-09 06:15:23
def random_int(min, max)
rand(max - min) + min
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
2014-04-23 05:07:51
Y aquí hay un punto de referencia rápido para #sample
y #rand
:
irb(main):014:0* Benchmark.bm do |x|
irb(main):015:1* x.report('sample') { 1_000_000.times { (1..100).to_a.sample } }
irb(main):016:1> x.report('rand') { 1_000_000.times { rand(1..100) } }
irb(main):017:1> end
user system total real
sample 3.870000 0.020000 3.890000 ( 3.888147)
rand 0.150000 0.000000 0.150000 ( 0.153557)
Entonces, hacer rand(a..b)
es lo correcto
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-06-26 15:14:56