Additionally, how can I format it as a string padded with zeros?
此外,如何将其格式化为填充了0的字符串?
15 个解决方案
#1
76
To generate the number call rand with the result of the expression "10 to the power of 10"
生成“10的10次方”表达式的数字调用rand
rand(10 ** 10)
To pad the number with zeros you can use the string format operator
要用0填充数字,可以使用字符串格式操作符
'%010d' % rand(10 ** 10)
or the rjust
method of string
或者是字符串的rjust方法
rand(10 ** 10).to_s.rjust(10,'0')
#2
47
I would like to contribute probably a simplest solution I know, which is a quite a good trick.
我想贡献一个我知道的最简单的方法,这是一个很好的技巧。
rand.to_s[2..11]
=> "5950281724"
#3
22
This is a fast way to generate a 10-sized string of digits:
这是一种快速生成10大小的数字串的方法:
10.times.map{rand(10)}.join # => "3401487670"
#4
10
The most straightforward answer would probably be
最直接的答案可能是
rand(1e9...1e10).to_i
兰特(1 e9…1 e10).to_i
The to_i
part is needed because 1e9
and 1e10
are actually floats:
to_i部分是必需的,因为1e9和1e10实际上是浮点数:
irb(main)> 1e9.class
=> Float
#5
6
Just because it wasn't mentioned, the Kernel#sprintf
method (or it's alias Kernel#format
in the Powerpack Library) is generally preferred over the String#%
method, as mentioned in the Ruby Community Style Guide.
仅仅因为没有提到,内核#sprintf方法(或者是Powerpack库中的别名内核#格式)通常优于String#%方法,正如Ruby社区风格指南中提到的那样。
Of course this is highly debatable, but to provide insight:
当然,这是有争议的,但为了提供见解:
The syntax of @quackingduck's answer would be
@quackingduck的语法应该是
# considered bad
'%010d' % rand(10**10)
# considered good
sprintf('%010d', rand(10**10))
The nature of this preference is primarily due to the cryptic nature of %
. It's not very semantic by itself and without any additional context it can be confused with the %
modulo operator.
这种偏好的性质主要是由于%的神秘性质。它本身并不是很语义化,没有任何附加上下文,它可以与% modulo操作符混淆。
Examples from the 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'
To make justice for String#%
, I personally really like using operator-like syntaxes instead of commands, the same way you would do your_array << 'foo'
over your_array.push('123')
.
要为字符串#%进行正义,我个人非常喜欢使用operator-like语法,而不是命令,就像您在您的_array.push(“123”)上执行your_array << foo >一样。
This just illustrates a tendency in the community, what's "best" is up to you.
这只是说明了社会上的一种倾向,什么是最好的取决于你。
More info in this blogpost.
更多信息请见这篇博文。
#6
6
Random number generation
Use Kernel#rand method:
使用内核#兰德方法:
rand(1_000_000_000..9_999_999_999) # => random 10-digits number
Random string generation
Use times
+ map
+ join
combination:
使用times + map + join组合:
10.times.map { rand(0..9) }.join # => random 10-digit string (may start with 0!)
Number to string conversion with padding
Use String#% method:
使用字符串# %方法:
"%010d" % 123348 # => "0000123348"
Password generation
Use KeePass password generator library, it supports different patterns for generating random password:
使用KeePass密码生成器库,支持生成随机密码的不同模式:
KeePass::Password.generate("d{10}") # => random 10-digit string (may start with 0!)
A documentation for KeePass patterns can be found here.
可以在这里找到关于KeePass模式的文档。
#7
5
DON'T USE rand.to_s[2..11].to_i
Why? Because here's what you can get:
为什么?因为你可以得到:
rand.to_s[2..9] #=> "04890612"
and then:
然后:
"04890612".to_i #=> 4890612
Note that:
注意:
4890612.to_s.length #=> 7
Which is not what you've expected!
这不是你所期望的!
To check that error in your own code, instead of .to_i
you may wrap it like this:
要在您自己的代码中检查这个错误,而不是.to_i,您可以这样包装它:
Integer(rand.to_s[2..9])
and very soon it will turn out that:
很快就会发现:
ArgumentError: invalid value for Integer(): "02939053"
So it's always better to stick to .center
, but keep in mind that:
所以最好还是坚持。中心,但要记住:
rand(9)
sometimes may give you 0
.
有时会得到0。
To prevent that:
预防:
rand(1..9)
which will always return something withing 1..9
range.
它总会返回一些东西。9范围。
I'm glad that I had good tests and I hope you will avoid breaking your system.
我很高兴我有很好的测试,我希望你不要破坏你的系统。
#8
3
I just want to modify first answer. rand (10**10)
may generate 9 digit random no if 0 is in first place. For ensuring 10 exact digit just modify
我只是想修改第一个答案。rand(10**10)可以产生9位随机数字no,如果0是第一位的话。为了确保10个精确的数字只是修改。
code = rand(10**10)
while code.to_s.length != 10
code = rand(11**11)
end
结束
#9
2
Here is an expression that will use one fewer method call than quackingduck's example.
这里有一个表达式,它将比quackingduck的示例少使用一个方法调用。
'%011d' % rand(1e10)
One caveat, 1e10
is a Float
, and Kernel#rand
ends up calling to_i
on it, so for some higher values you might have some inconsistencies. To be more precise with a literal, you could also do:
需要注意的是,1e10是一个浮点数,而内核#rand最终会调用to_i,因此对于一些更高的值,您可能会有一些不一致的地方。更准确地说,你也可以这样做:
'%011d' % rand(10_000_000_000) # Note that underscores are ignored in integer literals
#10
2
This technique works for any "alphabet"
这种技术适用于任何“字母表”
(1..10).map{"0123456789".chars.to_a.sample}.join
=> "6383411680"
#11
2
Simplest way to generate n digit random number -
生成n位数随机数的最简单方法
Random.new.rand((10**(n - 1))..(10**n))
generate 10 digit number number -
生成10位数字-
Random.new.rand((10**(10 - 1))..(10**10))
#12
1
rand(9999999999).to_s.center(10, rand(9).to_s).to_i
is faster than
是速度比
rand.to_s[2..11].to_i
You can use:
您可以使用:
puts Benchmark.measure{(1..1000000).map{rand(9999999999).to_s.center(10, rand(9).to_s).to_i}}
and
和
puts Benchmark.measure{(1..1000000).map{rand.to_s[2..11].to_i}}
in Rails console to confirm that.
在Rails控制台确认。
#13
1
An alternative answer, using the regexp-examples
ruby gem:
另一个答案,使用regexpe示例ruby gem:
require 'regexp-examples'
/\d{10}/.random_example # => "0826423747"
There's no need to "pad with zeros" with this approach, since you are immediately generating a String
.
不需要用这种方法“用0填充”,因为您马上就要生成一个字符串。
#14
0
This will work even on ruby 1.8.7:
这甚至可以在ruby 1.8.7中使用:
rand(9999999999).to_s.center(10, rand(9).to_s).to_i
兰特(9999999999).to_s。中心(10,兰德(9).to_s).to_i
#15
0
Try using the SecureRandom ruby library.
尝试使用SecureRandom ruby库。
It generates random numbers but the length is not specific.
它生成随机数,但长度不是特定的。
Go through this link for more information: http://ruby-doc.org/stdlib-2.1.2/libdoc/securerandom/rdoc/SecureRandom.html
浏览这个链接获得更多信息:http://ruby-doc.org/stdlib-2.1.2 libdoc/securerandom/r/securerandom.html
#1
76
To generate the number call rand with the result of the expression "10 to the power of 10"
生成“10的10次方”表达式的数字调用rand
rand(10 ** 10)
To pad the number with zeros you can use the string format operator
要用0填充数字,可以使用字符串格式操作符
'%010d' % rand(10 ** 10)
or the rjust
method of string
或者是字符串的rjust方法
rand(10 ** 10).to_s.rjust(10,'0')
#2
47
I would like to contribute probably a simplest solution I know, which is a quite a good trick.
我想贡献一个我知道的最简单的方法,这是一个很好的技巧。
rand.to_s[2..11]
=> "5950281724"
#3
22
This is a fast way to generate a 10-sized string of digits:
这是一种快速生成10大小的数字串的方法:
10.times.map{rand(10)}.join # => "3401487670"
#4
10
The most straightforward answer would probably be
最直接的答案可能是
rand(1e9...1e10).to_i
兰特(1 e9…1 e10).to_i
The to_i
part is needed because 1e9
and 1e10
are actually floats:
to_i部分是必需的,因为1e9和1e10实际上是浮点数:
irb(main)> 1e9.class
=> Float
#5
6
Just because it wasn't mentioned, the Kernel#sprintf
method (or it's alias Kernel#format
in the Powerpack Library) is generally preferred over the String#%
method, as mentioned in the Ruby Community Style Guide.
仅仅因为没有提到,内核#sprintf方法(或者是Powerpack库中的别名内核#格式)通常优于String#%方法,正如Ruby社区风格指南中提到的那样。
Of course this is highly debatable, but to provide insight:
当然,这是有争议的,但为了提供见解:
The syntax of @quackingduck's answer would be
@quackingduck的语法应该是
# considered bad
'%010d' % rand(10**10)
# considered good
sprintf('%010d', rand(10**10))
The nature of this preference is primarily due to the cryptic nature of %
. It's not very semantic by itself and without any additional context it can be confused with the %
modulo operator.
这种偏好的性质主要是由于%的神秘性质。它本身并不是很语义化,没有任何附加上下文,它可以与% modulo操作符混淆。
Examples from the 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'
To make justice for String#%
, I personally really like using operator-like syntaxes instead of commands, the same way you would do your_array << 'foo'
over your_array.push('123')
.
要为字符串#%进行正义,我个人非常喜欢使用operator-like语法,而不是命令,就像您在您的_array.push(“123”)上执行your_array << foo >一样。
This just illustrates a tendency in the community, what's "best" is up to you.
这只是说明了社会上的一种倾向,什么是最好的取决于你。
More info in this blogpost.
更多信息请见这篇博文。
#6
6
Random number generation
Use Kernel#rand method:
使用内核#兰德方法:
rand(1_000_000_000..9_999_999_999) # => random 10-digits number
Random string generation
Use times
+ map
+ join
combination:
使用times + map + join组合:
10.times.map { rand(0..9) }.join # => random 10-digit string (may start with 0!)
Number to string conversion with padding
Use String#% method:
使用字符串# %方法:
"%010d" % 123348 # => "0000123348"
Password generation
Use KeePass password generator library, it supports different patterns for generating random password:
使用KeePass密码生成器库,支持生成随机密码的不同模式:
KeePass::Password.generate("d{10}") # => random 10-digit string (may start with 0!)
A documentation for KeePass patterns can be found here.
可以在这里找到关于KeePass模式的文档。
#7
5
DON'T USE rand.to_s[2..11].to_i
Why? Because here's what you can get:
为什么?因为你可以得到:
rand.to_s[2..9] #=> "04890612"
and then:
然后:
"04890612".to_i #=> 4890612
Note that:
注意:
4890612.to_s.length #=> 7
Which is not what you've expected!
这不是你所期望的!
To check that error in your own code, instead of .to_i
you may wrap it like this:
要在您自己的代码中检查这个错误,而不是.to_i,您可以这样包装它:
Integer(rand.to_s[2..9])
and very soon it will turn out that:
很快就会发现:
ArgumentError: invalid value for Integer(): "02939053"
So it's always better to stick to .center
, but keep in mind that:
所以最好还是坚持。中心,但要记住:
rand(9)
sometimes may give you 0
.
有时会得到0。
To prevent that:
预防:
rand(1..9)
which will always return something withing 1..9
range.
它总会返回一些东西。9范围。
I'm glad that I had good tests and I hope you will avoid breaking your system.
我很高兴我有很好的测试,我希望你不要破坏你的系统。
#8
3
I just want to modify first answer. rand (10**10)
may generate 9 digit random no if 0 is in first place. For ensuring 10 exact digit just modify
我只是想修改第一个答案。rand(10**10)可以产生9位随机数字no,如果0是第一位的话。为了确保10个精确的数字只是修改。
code = rand(10**10)
while code.to_s.length != 10
code = rand(11**11)
end
结束
#9
2
Here is an expression that will use one fewer method call than quackingduck's example.
这里有一个表达式,它将比quackingduck的示例少使用一个方法调用。
'%011d' % rand(1e10)
One caveat, 1e10
is a Float
, and Kernel#rand
ends up calling to_i
on it, so for some higher values you might have some inconsistencies. To be more precise with a literal, you could also do:
需要注意的是,1e10是一个浮点数,而内核#rand最终会调用to_i,因此对于一些更高的值,您可能会有一些不一致的地方。更准确地说,你也可以这样做:
'%011d' % rand(10_000_000_000) # Note that underscores are ignored in integer literals
#10
2
This technique works for any "alphabet"
这种技术适用于任何“字母表”
(1..10).map{"0123456789".chars.to_a.sample}.join
=> "6383411680"
#11
2
Simplest way to generate n digit random number -
生成n位数随机数的最简单方法
Random.new.rand((10**(n - 1))..(10**n))
generate 10 digit number number -
生成10位数字-
Random.new.rand((10**(10 - 1))..(10**10))
#12
1
rand(9999999999).to_s.center(10, rand(9).to_s).to_i
is faster than
是速度比
rand.to_s[2..11].to_i
You can use:
您可以使用:
puts Benchmark.measure{(1..1000000).map{rand(9999999999).to_s.center(10, rand(9).to_s).to_i}}
and
和
puts Benchmark.measure{(1..1000000).map{rand.to_s[2..11].to_i}}
in Rails console to confirm that.
在Rails控制台确认。
#13
1
An alternative answer, using the regexp-examples
ruby gem:
另一个答案,使用regexpe示例ruby gem:
require 'regexp-examples'
/\d{10}/.random_example # => "0826423747"
There's no need to "pad with zeros" with this approach, since you are immediately generating a String
.
不需要用这种方法“用0填充”,因为您马上就要生成一个字符串。
#14
0
This will work even on ruby 1.8.7:
这甚至可以在ruby 1.8.7中使用:
rand(9999999999).to_s.center(10, rand(9).to_s).to_i
兰特(9999999999).to_s。中心(10,兰德(9).to_s).to_i
#15
0
Try using the SecureRandom ruby library.
尝试使用SecureRandom ruby库。
It generates random numbers but the length is not specific.
它生成随机数,但长度不是特定的。
Go through this link for more information: http://ruby-doc.org/stdlib-2.1.2/libdoc/securerandom/rdoc/SecureRandom.html
浏览这个链接获得更多信息:http://ruby-doc.org/stdlib-2.1.2 libdoc/securerandom/r/securerandom.html