The SitePoint Forums have moved.

You can now find them here.
This forum is now closed to new posts, but you can browse existing content.
You can find out more information about the move and how to open a new account (if necessary) here.
If you get stuck you can get support by emailing forums@sitepoint.com

If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Generating a Specified Length String of Random Numbers

This is going to sound like a homework question, but I swear I'm not in school. So bear with me.

Here's some pseudo-code that I wrote up.

# I want to be able to create a random numeric string that is the length
# specified by the user. I should take an integer as input and this should
# correspond to the length of the string. I should generate random
# numbers for each positional length until the string is equal to the length
# specified by the user.

Here's where I'm stuck:

Code:

# makes a new string with zero length
n = String.new
# function to return random numbers
# don't want any zeroes and I think
# i need to return the val as a string
# and not an integer hence the 'to_s'
def generateChar
i = rand(8) + 1
return i.to_s
end
# could be a 'while' - trying until
# call the generateChar function
# until the length of the new string
# is equal to 10. length here is hardcoded
# but eventually would be a var
until n.length = 10
n + generateChar()
return n
end
# yep, generateChar() function works
# puts generateChar()
puts n

Not sure where to go here. In PHP you can concatenate strings using the '.=' operator.

To concat in Ruby you use the '+' operator, but I think there's something else wrong in what I'm trying to do.

Love your articles, by the way. And the PHP slides - the SimpleTest slides immeasurably helpful.

Can you explain that just a little? I think I see what you're doing, but I don't really get it. There's a range in there and a new method 'collect' that I've never used. Didn't dawn on me to use 'join.'

I just made the first character, then I used the range to specify how many iterate. collect took a block which returned another digit as a string. join took that resulting array and assembled it back into a string.

Also, take this with a grain of salt, I am probably just as much of a newby at Ruby as you are.