Dakota V. Dakota V. - 7 months ago 14
Ruby Question

Generating a string of a specific length, then filling with a value

I am attempting to take a value

x
and generate a string with the length
x
so that I will have a value like
"00000"
. I want to manipulate those values and return a value such as
"22222"
,
"11111"
, or
"00000"
. I attempted manipulating an array, and I will do an array if necessary, but I prefer to avoid that as that seems to get unnecessarily lengthy.

Answer
def string_gen(length.to_i)
  chars = %w(a b c d e f g h i j k l m n o p q r s t u w x y z)
  random_string = chars.to_a[rand(chars.length)].join
  puts random_string
end

string_gen(6)
#<= "jahsyd"

If you want to do it more then one time add a .times loop:

def string_gen(length.to_i)
  chars = %w(a b c d e f g h i j k l m n o p q r s t u w x y z)
  5.times do
    random_string = chars.to_a[rand(chars.length)].join
    puts random_string
  end
end

This is completely untested.