我目前正在爲「 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
SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz')
來自Devise的東西code
個人2美分: token
def token(length=16) chars = [*('A'..'Z'), *('a'..'z'), *(0..9)] (0..length).map {chars.sample}.join end
只是在這裏加個人美分... 字符串
def random_string(length = 8) rand(32**length).to_s(32) end
我不記得我在哪裏找到的,但對我來講彷佛是最好,最省力的過程: string
def random_string(length=10) chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789' password = '' length.times { password << chars[rand(chars.size)] } password end
require 'securerandom' SecureRandom.urlsafe_base64(9)