如何在Ruby中生成随机字符串

我目前正在为“ A” ..“ Z”生成一个8个字符的伪随机大写字符串: dom

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

但它看起来并不干净,而且因为它不是单个语句,所以不能做为参数传递。 为了得到大小写混合的字符串“ a” ..“ z”加上“ A” ..“ Z”,我将其更改成: ui

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

但看起来像垃圾 url

有谁有更好的方法? spa


#1楼

SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz')

来自Devise的东西code


#2楼

个人2美分: token

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

#3楼

只是在这里加个人美分... 字符串

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

#4楼

我不记得我在哪里找到的,但对我来讲彷佛是最好,最省力的过程: string

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

#5楼

require 'securerandom'
SecureRandom.urlsafe_base64(9)
相关文章
相关标签/搜索