7bdb696ac0f589522c9ed31a1b24057b

So this is kind of trivial but I can't help but think there is a better way. I've included a couple different ways.

1
2
3
4
5
6
7
8
alphanumerics = [*('0'..'9')] + [*('A'..'Z')] + [*('a'..'z')]
(0...25).map { alphanumerics[Kernel.rand(alphanumerics.size)] }.join

alphanumerics = [('0'..'9'),('A'..'Z'),('a'..'z')].map {|range| range.to_a}.flatten
(0...25).map { alphanumerics[Kernel.rand(alphanumerics.size)] }.join

alphanumerics = ('0'..'9').to_a + ('A'..'Z').to_a + ('a'..'z').to_a
(0...25).map { alphanumerics[Kernel.rand(alphanumerics.size)] }.join

Refactorings

No refactoring yet !

Avatar

VitalieL

July 3, 2008, July 03, 2008 07:47, permalink

No rating. Login to rate!

You will need to filter numbers from [58-64] to avoid \,~ chars

1
2
3
4
5
6
7
irb(main):009:0> a = '-'*25
=> "-------------------------"
irb(main):010:0> 25.times {|x| a[x] = rand(90) + 48}
=> 25
irb(main):011:0> a
=> ">Ne~r4[3Skd2\201s6<\\THOD}QYn"
irb(main):012:0>
Avatar

Ryan Bates

July 3, 2008, July 03, 2008 16:02, permalink

2 ratings. Login to rate!

In the past I've added a random_string method to the String class which can take a length and array of chars to use. I wouldn't say it's much of an improvement, but some might find it helpful.

1
2
3
4
5
6
class String
  def self.random_string(length = 8, chars = nil)
    chars ||= ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
    Array.new(length) { chars[rand(chars.size)] }.join
  end
end
C56c078159148c1e3ac494ad8a7a74e0

Raghu Srinivasan

July 6, 2008, July 06, 2008 19:46, permalink

No rating. Login to rate!

Here's what I've been using as a library function

1
2
3
4
5
  def random_string(length)
    chars = ("a".."z").to_a + ("0".."9").to_a
    randomstring = ""
    1.upto(length) { |i| randomstring << chars[rand(chars.size-1)] }
  end
1a18d240b68c5cad64a205a8c17442a7

Justin Jones

July 9, 2008, July 09, 2008 20:28, permalink

1 rating. Login to rate!

Just for something a little different :)

1
2
require 'digest/sha1'
Digest::SHA1.hexdigest(Time.now.to_s)

Your refactoring





Format Copy from initial code

or Cancel