【问题标题】:Combining two different 'ranges' to one in ruby在红宝石中将两个不同的“范围”组合为一个
【发布时间】:2014-01-28 11:26:07
【问题描述】:
我想将 rails 中的两个不同范围组合成一个数组。有没有相同的短方法?
我正在编写代码来生成随机的字母数字字符串。
现在我有:
('a'..'z').to_a.shuffle.first(16).join
我也尝试过类似的方法(没用):
('a'..'z').to_a.push('0'..'9').shuffle.first(16).join
【问题讨论】:
标签:
ruby-on-rails
arrays
shuffle
range
【解决方案1】:
我有一个更好的方法:使用 splat 运算符!
[*'0'..'9', *'a'..'z', *'A'..'Z'].sample(16).join
【解决方案2】:
更优雅的方式:
['a'..'z', '0'..'9'].flat_map(&:to_a).sample(16).join
【解决方案3】:
试试这个:
('a'..'z').to_a.push(*('0'..'9').to_a).shuffle.first(16).join
【解决方案4】:
或者试试这个:
('a'..'z').to_a.concat(('0'..'9').to_a).shuffle.first(16).join
【解决方案5】:
公认的.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"
【解决方案6】:
可以使用 map 将 Ranges 合并成一个数组,比如
[ 'A'..'Z', 'a'..'z', '0'..'9' ].map { |r| Array(r) }.inject( :+ )
所以在你的例子中是
['a'..'z','0'..'9'].map{|r|Array(r)}.inject(:+).shuffle.first(16).join