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

六月ゝ 毕业季﹏ 提交于 2019-12-22 12:12:22

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

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

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

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

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

但看起来像垃圾

有谁有更好的方法?


#1楼

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

来自Devise的东西


#2楼

我的2美分:

  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楼

我不记得我在哪里找到的,但对我来说似乎是最好,最省力的过程:

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

#5楼

require 'securerandom'
SecureRandom.urlsafe_base64(9)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!