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 09:55

Given:

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

Single expression, can be passed as an argument, allows duplicate characters:

Array.new(len) { chars.sample }.join
查看更多
孤独总比滥情好
3楼-- · 2019-01-01 09:55

I was doing something like this recently to generate an 8 byte random string from 62 characters. The characters were 0-9,a-z,A-Z. I had an array of them as was looping 8 times and picking a random value out of the array. This was inside a rails app.

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

The weird thing is that I got good number of duplicates. Now randomly this should pretty much never happen. 62^8 is huge, but out of 1200 or so codes in the db i had a good number of duplicates. I noticed them happening on hour boundaries of each other. In other words I might see a duple at 12:12:23 and 2:12:22 or something like that...not sure if time is the issue or not.

This code was in the before create of an activerecord object. Before the record was created this code would run and generate the 'unique' code. Entries in the db were always produced reliably, but the code (str in the above line) was being duplicated much too often.

I created a script to run through 100000 iterations of this above line with small delay so it would take 3-4 hours hoping to see some kind of repeat pattern on an hourly basis, but saw nothing. I have no idea why this was happening in my rails app.

查看更多
像晚风撩人
4楼-- · 2019-01-01 09:56

I can't remember where I found this, but it seems like the best and the least process intensive to me:

def random_string(length=10)
  chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789'
  password = ''
  length.times { password << chars[rand(chars.size)] }
  password
end
查看更多
美炸的是我
5楼-- · 2019-01-01 09:58

Here is one line simple code for random string with length 8

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

You can also use it for random password having length 8

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

i hope it will help and amazing.

查看更多
琉璃瓶的回忆
6楼-- · 2019-01-01 09:58
SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz')

Something from Devise

查看更多
只靠听说
7楼-- · 2019-01-01 09:59
[*('A'..'Z')].sample(8).join

Generate a random 8 letter string (e.g. NVAYXHGR)

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

Generate a random 8 character string (e.g. 3PH4SWF2), excludes 0/1/I/O. Ruby 1.9

查看更多
登录 后发表回答