如何在ruby中生成随机的10位数字?

问题描述 投票:58回答:21

另外,我如何将其格式化为用零填充的字符串?

ruby random
21个回答
81
投票

要生成数字调用rand,结果为“10到10的幂”

rand(10 ** 10)

要用零填充数字,可以使用字符串格式运算符

'%010d' % rand(10 ** 10)

rjust字符串方法

rand(10 ** 10).to_s.rjust(10,'0')  

2
投票

这是一个表达式,它将比quackingduck的示例使用少一个方法调用。

'%011d' % rand(1e10)

一个警告,1e10是一个FloatKernel#rand最终调用to_i,所以对于一些更高的值,你可能会有一些不一致。为了更精确地使用文字,您还可以:

'%011d' % rand(10_000_000_000) # Note that underscores are ignored in integer literals

2
投票

尝试使用SecureRandom ruby​​库。

它生成随机数,但长度不是特定的。

有关更多信息,请访问此链接:http://ruby-doc.org/stdlib-2.1.2/libdoc/securerandom/rdoc/SecureRandom.html


2
投票

这种技术适用于任何“字母”

(1..10).map{"0123456789".chars.to_a.sample}.join
=> "6383411680"

1
投票
rand(9999999999).to_s.center(10, rand(9).to_s).to_i

比...更快

rand.to_s[2..11].to_i

您可以使用:

puts Benchmark.measure{(1..1000000).map{rand(9999999999).to_s.center(10, rand(9).to_s).to_i}}

puts Benchmark.measure{(1..1000000).map{rand.to_s[2..11].to_i}}

在Rails控制台中确认。


1
投票

另一个答案,使用regexp-examples红宝石宝石:

require 'regexp-examples'

/\d{10}/.random_example # => "0826423747"

使用这种方法不需要“用零填充”,因为您立即生成String


1
投票

只需在下面直截了当使用。

rand(10 ** 9...10 ** 10)

只需在下面的IRB上测试它。

(1..1000).each { puts rand(10 ** 9...10 ** 10) }

0
投票

这甚至可以在ruby 1.8.7上运行:

rand(9999999999).to_s.center(10,rand(9).to_s).to_i


0
投票

更好的方法是使用Array.new()而不是.times.map。 Rubocop推荐它。

例:

string_size = 9
Array.new(string_size) do
   rand(10).to_s
end

Rubocop,时间地图:

https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Performance/TimesMap


0
投票

随机10个数字:

require 'string_pattern'
puts "10:N".gen

0
投票

在我的情况下,我的模型中的数字必须是唯一的,所以我添加了检查块。

  module StringUtil
    refine String.singleton_class do
      def generate_random_digits(size:)
        proc = lambda{ rand.to_s[2...(2 + size)] }
        if block_given?
          loop do
            generated = proc.call
            break generated if yield(generated) # check generated num meets condition
          end
        else
          proc.call
        end
      end
    end
  end
  using StringUtil
  String.generate_random_digits(3) => "763"
  String.generate_random_digits(3) do |num|
    User.find_by(code: num).nil?
  end => "689"(This is unique in Users code)

52
投票

我想提供一个我认识的最简单的解决方案,这是一个非常好的技巧。

rand.to_s[2..11] 
 => "5950281724"

0
投票

('%010d' % rand(0..9999999999)).to_s

要么

"#{'%010d' % rand(0..9999999999)}"


0
投票

要生成随机的10位数字符串:

# This generates a 10-digit string, where the
# minimum possible value is "0000000000", and the
# maximum possible value is "9999999999"
SecureRandom.random_number(10**10).to_s.rjust(10, '0')

这里有更多关于正在发生的事情的细节,通过解释变量将单行分成多行来显示:

  # Calculate the upper bound for the random number generator
  # upper_bound = 10,000,000,000
  upper_bound = 10**10

  # n will be an integer with a minimum possible value of 0,
  # and a maximum possible value of 9,999,999,999
  n = SecureRandom.random_number(upper_bound)

  # Convert the integer n to a string
  # unpadded_str will be "0" if n == 0
  # unpadded_str will be "9999999999" if n == 9_999_999_999
  unpadded_str = n.to_s

  # Pad the string with leading zeroes if it is less than
  # 10 digits long.
  # "0" would be padded to "0000000000"
  # "123" would be padded to "0000000123"
  # "9999999999" would not be padded, and remains unchanged as "9999999999"
  padded_str = unpadded_str.rjust(10, '0')

27
投票

这是生成10大小数字字符串的快速方法:

10.times.map{rand(10)}.join # => "3401487670"

13
投票

最简单的答案可能是

rand(1e9...1e10).to_i

需要to_i部分,因为1e91e10实际上是浮动的:

irb(main)> 1e9.class
=> Float

8
投票

不要使用rand.to_s[2..11].to_i

为什么?因为这是你能得到的:

rand.to_s[2..9] #=> "04890612"

然后:

"04890612".to_i #=> 4890612

注意:

4890612.to_s.length #=> 7

这不是你所期望的!

要在您自己的代码中检查该错误,而不是.to_i,您可以像这样包装它:

Integer(rand.to_s[2..9])

很快就会发现:

ArgumentError: invalid value for Integer(): "02939053"

所以坚持使用.center总是更好,但请记住:

rand(9) 

有时可能会给你0

为了防止:

rand(1..9)

这将永远返回1..9范围内的东西。

我很高兴我有很好的测试,我希望你能避免破坏你的系统。


7
投票

仅仅因为没有提及,Kernel#sprintf方法(或Kernel#format中的别名Powerpack Library)通常优于String#%方法,如Ruby Community Style Guide中所述。

当然这是值得商榷的,但要提供见解:

@ quackingduck的答案的语法是

# considered bad
'%010d' % rand(10**10)

# considered good
sprintf('%010d', rand(10**10))

这种偏好的本质主要是由于%的神秘本质。它本身并不是非常语义,没有任何额外的上下文,它可以与%模运算符混淆。

来自Style Guide的例子:

# bad
'%d %d' % [20, 10]
# => '20 10'

# good
sprintf('%d %d', 20, 10)
# => '20 10'

# good
sprintf('%{first} %{second}', first: 20, second: 10)
# => '20 10'

format('%d %d', 20, 10)
# => '20 10'

# good
format('%{first} %{second}', first: 20, second: 10)
# => '20 10'

为了为String#%伸张正义,我个人非常喜欢使用类似运算符的语法而不是命令,就像你在your_array << 'foo'上使用your_array.push('123')一样。

这恰恰说明了社区中的一种趋势,“最好的”取决于你。

更多信息在this blogpost


7
投票

随机数生成

使用Kernel#rand方法:

rand(1_000_000_000..9_999_999_999) # => random 10-digits number

随机字符串生成

使用times + map + join组合:

10.times.map { rand(0..9) }.join # => random 10-digit string (may start with 0!)

使用填充进行字符串转换的数字

使用String#%方法:

"%010d" % 123348 # => "0000123348"

密码生成

使用KeePass password generator库,它支持生成随机密码的不同模式:

KeePass::Password.generate("d{10}") # => random 10-digit string (may start with 0!)

可以找到关于KeePass模式的文档here


3
投票

我只是想修改第一个答案。如果0位于第一位,rand (10**10)可能会产生9位随机数。确保10个确切的数字只需修改

code = rand(10**10)
while code.to_s.length != 10
code = rand(11**11)

结束


3
投票

生成n位随机数的最简单方法 -

Random.new.rand((10**(n - 1))..(10**n))

生成10位数字 -

Random.new.rand((10**(10 - 1))..(10**10))
© www.soinside.com 2019 - 2024. All rights reserved.