1

I need a string that is str_len characters long for testing.

What ways are there that are more elegant (and possibly faster) ways of building it than the following:

  long_str = ''
  (str_len + 1).times do
    long_str << 'a'
  end

It would be helpful if the algorithm could also randomise the content of the string (i.e. use any character).

Peter Nixey
  • 14,568
  • 11
  • 71
  • 118
  • 1
    Check this [link](http://stackoverflow.com/questions/88311/how-best-to-generate-a-random-string-in-ruby) – Stobbej Nov 01 '11 at 13:55

2 Answers2

4

Use the * method on the String class.

long_str = 'a' * 6
# => 'aaaaaa'
Chris Ledet
  • 11,190
  • 6
  • 37
  • 47
3

This produces a four letter long random string with the characters a to z.

charset=('a'..'z').to_a
srand(124931)
puts (0...4).map{ charset.to_a[rand(charset.size)] }.join 

Remove or replace the srand(124931) with srand() before actually using this code.

Jonas Elfström
  • 28,718
  • 6
  • 66
  • 102