目前,我正在产生一个8字伪随机的大写字符串为"A".."Z":

value = ""; 8.times{value  << (65 + rand(25)).chr}

但是它没看起来很干净,它不能通过作为一个论点,因为它不是一个单一的发言。得到一个混合的情况下string"a".."z"附加"一个".."Z",我改变它:

value = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr}

但是它看起来像垃圾。

没有任何人有一个更好的方法吗?

有帮助吗?

解决方案

(0...8).map { (65 + rand(26)).chr }.join

我花太多时间打高尔夫球。

(0...50).map { ('a'..'z').to_a[rand(26)] }.join

和最后那个是更加混乱,而是更灵活和废物更少的周期:

o = [('a'..'z'), ('A'..'Z')].map(&:to_a).flatten
string = (0...50).map { o[rand(o.length)] }.join

其他提示

为什么不使用SecureRandom?

require 'securerandom'
random_string = SecureRandom.hex

# outputs: 5b5cd0da3121fc53b4bc84d0c8af2e81 (i.e. 32 chars of 0..9, a..f)

SecureRandom还有一些方法,用于:

  • base64
  • random_bytes
  • random_number

参见: http://ruby-doc.org/stdlib-1.9.2/libdoc/securerandom/rdoc/SecureRandom.html

我使用这个用于产生随机URL友好的琴弦与保证的最大的长度:

rand(36**length).to_s(36)

它产生随机的字符串的小写的a-z and0-9.它不是定制的,但这是短和清洁。

这个解决方案产生串简单易读的字符用于激活代码;我不想让人混淆8B,1I,0O,L1,等等。

# Generates a random string from a set of easily readable characters
def generate_activation_code(size = 6)
  charset = %w{ 2 3 4 6 7 9 A C D E F G H J K M N P Q R T V W X Y Z}
  (0...size).map{ charset.to_a[rand(charset.size)] }.join
end

其他人已经提到类似的东西,但这种使用URL安全功能。

require 'securerandom'
p SecureRandom.urlsafe_base64(5) #=> "UtM7aa8"
p SecureRandom.urlsafe_base64 #=> "UZLdOkzop70Ddx-IJR0ABg"
p SecureRandom.urlsafe_base64(nil, true) #=> "i0XQ-7gglIsHGV2_BNPrdQ=="

结果可能包含A-Z,a-z,0-9、"-"和"_"."="也用,如果填充的是真的。

[*('A'..'Z')].sample(8).join

产生一个随机的8个字母字符串(例如NVAYXHGR)

([*('A'..'Z'),*('0'..'9')]-%w(0 1 I O)).sample(8).join

随机产生一个8字符串(例如3PH4SWF2),不包括0/1/I/O.Ruby1.9

由于红宝石2.5真的很容易用 SecureRandom.alphanumeric:

len = 8
SecureRandom.alphanumeric(len)
=> "larHSsgL"

产生随机的字符串中含有A-Z,A-z and0-9因此应适用在大多数使用情况。和他们产生随机的安全,这可能是一个好处,也。


编辑:一个基准比较的解决方案具有最大的"顶":

require 'benchmark'
require 'securerandom'

len = 10
n = 100_000

Benchmark.bm(12) do |x|
  x.report('SecureRandom') { n.times { SecureRandom.alphanumeric(len) } }
  x.report('rand') do
    o = [('a'..'z'), ('A'..'Z'), (0..9)].map(&:to_a).flatten
    n.times { (0...len).map { o[rand(o.length)] }.join }
  end
end

                   user     system      total        real
SecureRandom   0.429442   0.002746   0.432188 (  0.432705)
rand           0.306650   0.000716   0.307366 (  0.307745)

所以 rand 解决方案只需要约3/4的时间 SecureRandom.可能会问题,如果你的生成真了很多串,但是如果你只是创造一些随机的字符串时我总是与更安全的执行情况(因为它也是更容易的呼吁,并更明确的).

我不记得我找到这一点,但这似乎是最好的和最密集的过程,对我说:

def random_string(length=10)
  chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789'
  password = ''
  length.times { password << chars[rand(chars.size)] }
  password
end
require 'securerandom'
SecureRandom.urlsafe_base64(9)

如果你想要一串的指定的长度,使用:

require 'securerandom'
randomstring = SecureRandom.hex(n)

它将产生一个随机的字符串的长度 2n 含有 0-9a-f

Array.new(n){[*"0".."9"].sample}.join, 其中n=8在你的情况。

广义: Array.new(n){[*"A".."Z", *"0".."9"].sample}.join, 等等。-从 答案

require 'sha1'
srand
seed = "--#{rand(10000)}--#{Time.now}--"
Digest::SHA1.hexdigest(seed)[0,8]

这里是一个行简单的代码随机的字符串的长度8

 random_string = ('0'..'z').to_a.shuffle.first(8).join

你也可以使用它随机的密码具有长8

random_password = ('0'..'z').to_a.shuffle.first(8).join

我希望它将帮助和惊人的。

Ruby1.9+:

ALPHABET = ('a'..'z').to_a
#=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

10.times.map { ALPHABET.sample }.join
#=> "stkbssowre"

# or

10.times.inject('') { |s| s + ALPHABET.sample }
#=> "fdgvacnxhc"

这是一个简单的代码随机的密码lenth8

rand_password=('0'..'z').to_a.shuffle.first(8).join

希望这将有所帮助。

注意: rand 是可预测的攻击和因此可能不安全。你绝对应该利用SecureRandom如果这是用于生成密码。我使用这样的事情:

length = 10
characters = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a

password = SecureRandom.random_bytes(length).each_char.map do |char|
  characters[(char.ord % characters.length)]
end.join

另一种方法我喜欢用

 rand(2**256).to_s(36)[0..7]

加入我,如果你真偏执的正确串的长度:

 rand(2**256).to_s(36).ljust(8,'a')[0..7]
SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz')

东西从制定

我认为这是一个很好的平衡的简明、清晰和易于修改。

characters = ('a'..'z').to_a + ('A'..'Z').to_a
# Prior to 1.9, use .choice, not .sample
(0..8).map{characters.sample}.join

很容易地修改

例如,其中包括数字:

characters = ('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a

大写hexadecimal:

characters = ('A'..'F').to_a + (0..9).to_a

对于一个真正的系列令人印象深刻的字:

characters = (32..126).to_a.pack('U*').chars.to_a

刚刚加入我分这里...

def random_string(length = 8)
  rand(32**length).to_s(32)
end

你可以使用 String#random 从方方面面的红宝石宝石 facets:

https://github.com/rubyworks/facets/blob/126a619fd766bc45588cac18d09c4f1927538e33/lib/core/facets/string/random.rb

它基本上不会这样的:

class String
  def self.random(len=32, character_set = ["A".."Z", "a".."z", "0".."9"])
    characters = character_set.map { |i| i.to_a }.flatten
    characters_len = characters.length
    (0...len).map{ characters[rand(characters_len)] }.join
  end
end

我最喜欢的是 (:A..:Z).to_a.shuffle[0,8].join.注意洗牌需要红宝石>1.9.

这个解决方案需要外部的依赖,但似乎比另一个。

  1. 安装的宝石 骗子
  2. Faker::Lorem.characters(10) # => "ang9cbhoa8"

鉴于:

chars = [*('a'..'z'),*('0'..'9')].flatten

单的表达,可以通过作为参数,允许重复的字:

Array.new(len) { chars.sample }.join

我在做的事这样的最近产生的一个8字节的随机的字符串从62个字符。人物是0-9,a-z,A-Z。我有一阵他们因为是循环的8倍和挑选一个随机的价值。这是内部的一个轨道应用程序。

str = '' 8.times {|i| str << ARRAY_OF_POSSIBLE_VALUES[rand(SIZE_OF_ARRAY_OF_POSSIBLE_VALUES)] }

奇怪的是,我有很多的重复。现在随机这应该相当多的永远不会发生。62^8是巨大的,但是1200或使码在数据库我有一个好的数量的重复。我注意到它们发生在小时的边界。换句话说我可能会看到一个复中午12:12:23和2:12:22或类似的东西...不确定,如果时间的问题或者没有。

这个代码之前创建一个email对象。之前的记录的建立是这个代码会运行和产生的'独特代码。条目的数据库始终产生可靠,但是代码(str在上述行)正在重复太经常。

我创建了一个脚本运行通过100000迭代的这个上述行与小延迟,所以它将需要3-4小时希望能够看到某种重复的模式每小时的基础上,但什么也没看见。我不知道为什么这是发生在我的轨道程序。

''.tap {|v| 4.times { v << ('a'..'z').to_a.sample} }

我2分:

  def token(length=16)
    chars = [*('A'..'Z'), *('a'..'z'), *(0..9)]
    (0..length).map {chars.sample}.join
  end

我只是写一个小宝石 random_token 到产生随机标记对于大多数使用的情况下,享受~

https://github.com/sibevin/random_token

用这种方法可以通过在一个abitrary长。它的设置作为一种默认值6.

def generate_random_string(length=6)
  string = ""
  chars = ("A".."Z").to_a
  length.times do
    string << chars[rand(chars.length-1)]
  end
  string
end

我喜欢雷达的最好的答案,迄今为止,我想。我调整一点像这样:

CHARS = ('a'..'z').to_a + ('A'..'Z').to_a
def rand_string(length=8)
  s=''
  length.times{ s << CHARS[rand(CHARS.length)] }
  s
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top