本文介绍了如何在Ruby中生成a和b之间的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
To generate a random number between 3 and 10, for example, I use: rand(8) + 3
Is there a nicer way to do this (something like rand(3, 10)) ?
解决方案UPDATE: Ruby 1.9.3 Kernel#rand also accepts ranges
rand(a..b)www.rubyinside/ruby-1-9-3-introduction-and-changes-5428.html
Converting to array may be too expensive, and it's unnecessary.
(a..b).to_a.sampleOr
[*a..b].sample
Array#sample
Standard in Ruby 1.8.7+. Note: was named #choice in 1.8.7 and renamed in later versions.
But anyway, generating array need resources, and solution you already wrote is the best, you can do.
更多推荐
如何在Ruby中生成a和b之间的随机数?
发布评论