Ruby on rails 结合两个不同的';范围';用红宝石做的
我想将rails中的两个不同范围合并到一个数组中。对于同样的问题,有什么简单的方法吗 我正在编写生成随机字母数字字符串的代码 现在我有:Ruby on rails 结合两个不同的';范围';用红宝石做的,ruby-on-rails,arrays,shuffle,range,Ruby On Rails,Arrays,Shuffle,Range,我想将rails中的两个不同范围合并到一个数组中。对于同样的问题,有什么简单的方法吗 我正在编写生成随机字母数字字符串的代码 现在我有: ('a'..'z').to_a.shuffle.first(16).join 我也尝试过类似的方法(不起作用): 试试这个: ('a'..'z').to_a.push(*('0'..'9').to_a).shuffle.first(16).join 或者试试这个: ('a'..'z').to_a.concat(('0'..'9').to_a).shuffl
('a'..'z').to_a.shuffle.first(16).join
我也尝试过类似的方法(不起作用):
试试这个:
('a'..'z').to_a.push(*('0'..'9').to_a).shuffle.first(16).join
或者试试这个:
('a'..'z').to_a.concat(('0'..'9').to_a).shuffle.first(16).join
可以使用map将范围合并到数组中,例如
[ 'A'..'Z', 'a'..'z', '0'..'9' ].map { |r| Array(r) }.inject( :+ )
所以在你的例子中是
['a'..'z','0'..'9'].map{|r|Array(r)}.inject(:+).shuffle.first(16).join
我有一个更好的方法:使用splat操作符
[*'0'..'9', *'a'..'z', *'A'..'Z'].sample(16).join
更优雅的方式:
['a'..'z', '0'..'9'].flat_map(&:to_a).sample(16).join
接受的
.sample
解决方案的问题在于,它们在生成字符串时从不重复相同的字符
> (0..9).to_a.sample(10).join
=> "0463287195"
# note you will never see the same number twice in the string
> (0..9).to_a.sample(15).join
=> "1704286395"
# we have exhausted the input range and only get back 10 characters
如果这是一个问题,您可以多次取样:
> Array.new(10) { (0..9).to_a.sample }.join
=> "2540730755"
至于.shuffle
方法,它们很好,但对于大型输入数组来说,计算成本可能会很高
生成短随机字符串的最简单/最佳方法可能是使用SecureRandom模块:
> require 'securerandom'
=> true
> SecureRandom.hex(10)
=> "1eaefe7829b3919b385a"
整洁的感谢@kmikaelI发现这个解决方案是最优雅的,代码是不言自明的!
> require 'securerandom'
=> true
> SecureRandom.hex(10)
=> "1eaefe7829b3919b385a"