Monday, January 24, 2011

generate a random string in rails

1:
o = [('a'..'z'),('A'..'Z')].map{|i| i.to_a}.flatten;
string = (0..50).map{ o[rand(o.length)] }.join;




2:
Why not use SecureRandom, provided by ActiveSupport?
require 'active_support/secure_random'
random_string = ActiveSupport::SecureRandom.hex(16)
# outputs: 5b5cd0da3121fc53b4bc84d0c8af2e81
SecureRandom also has methods for:
base64
hex
random_bytes
random_number
see: http://api.rubyonrails.org/classes/ActiveSupport/SecureRandom.html



3:
This solution generates a string of easily readable characters for activation codes; I didn't want people confusing 8 with B, 1 with I, 0 with O, etc.

# Generates a random string from a set of easily readable characters
def generate_activation_code(size = 6)
charset = %w{ 2 3 4 6 7 9 A C D E F G H J K L M N P Q R T V W X Y Z}
(0...size).map{ charset.to_a[rand(charset.size)] }.join
end


4:
Can't remember where I found this, but seemed the best to me and least process intense:

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



5:
`pwgen 8 1`.chomp



6:
I use this for generating random url friendly strings.

rand(32**length).to_s(32)
It generates random strings of lowercase a-z and 0-9. It's not very customizable but it's short and clean.


7:
Another method I like to use

rand(2**256).to_s(36)[0..7]
Add ljust if you are really paranoid about the correct string length:

rand(2**256).to_s(36).ljust(8,'a')[0..7]




8:
To make your first into one statement:

(0...8).collect { |n| value << (65 + rand(25)).chr }.join()




9:
With this method you can pass in an abitrary length. It's set as a default as 6.

def generate_random_string(length=6)
string = ""
chars = ("A".."Z").to_a
length.times do
string << chars[rand(chars.length-1)]
end
string
end



10:
ALPHABET = ('a'..'z').to_a
10.times.map{ ALPHABET.sample }.join
10.times.inject(''){|s| s << ALPHABET.sample }





11:

No comments:

Post a Comment