How to generate a random string in Ruby

2019-01-01 09:45发布

I'm currently generating an 8-character pseudo-random uppercase string for "A" .. "Z":

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

but it doesn't look clean, and it can't be passed as an argument since it isn't a single statement. To get a mixed-case string "a" .. "z" plus "A" .. "Z", I changed it to:

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

but it looks like trash.

Does anyone have a better method?

30条回答
柔情千种
2楼-- · 2019-01-01 10:09
require 'securerandom'
SecureRandom.urlsafe_base64(9)
查看更多
不流泪的眼
3楼-- · 2019-01-01 10:09

Just adding my cents here...

def random_string(length = 8)
  rand(32**length).to_s(32)
end
查看更多
看淡一切
4楼-- · 2019-01-01 10:11

If you want a string of specified length, use:

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

It will generate a random string of length 2n containing 0-9 and a-f

查看更多
路过你的时光
5楼-- · 2019-01-01 10:11
''.tap {|v| 4.times { v << ('a'..'z').to_a.sample} }
查看更多
浅入江南
6楼-- · 2019-01-01 10:15

Be aware: rand is predictable for an attacker and therefore probably insecure. You should definitely use SecureRandom if this is for generating passwords. I use something like this:

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
查看更多
泛滥B
7楼-- · 2019-01-01 10:15

you can use String#random from the Facets of Ruby Gem facets:

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

it basically does this:

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
查看更多
登录 后发表回答