Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > Generate randon string of fixed length (in bytes)

Reply
Thread Tools

Generate randon string of fixed length (in bytes)

 
 
Iñaki Baz Castillo
Guest
Posts: n/a
 
      01-27-2011
Hi, I use the following method to generate a random string:

def gen_token(len=3D6)
rand(36**len).to_s(36)
end

It's the most efficiente way I've found. However even if the parameter
is 6, the method sometimes returns a string of lenght 5, 4...

Is there an efficient way to a random string with fixed length? (I
don't want to check the resulting length and then append some other
byte....).

Thanks a lot.

--=20
I=C3=B1aki Baz Castillo
<>

 
Reply With Quote
 
 
 
 
Iñaki Baz Castillo
Guest
Posts: n/a
 
      01-27-2011
2011/1/27 I=C3=B1aki Baz Castillo <>:
> Hi, I use the following method to generate a random string:
>
> =C2=A0 =C2=A0def gen_token(len=3D6)
> =C2=A0 =C2=A0 =C2=A0rand(36**len).to_s(36)
> =C2=A0 =C2=A0end
>
> It's the most efficiente way I've found. However even if the parameter
> is 6, the method sometimes returns a string of lenght 5, 4...
>
> Is there an efficient way to a random string with fixed length? (I
> don't want to check the resulting length and then append some other
> byte....).


In fact, what I need is to generate a Base64 encoded string of a fixed
length. And I've found right now the SecureRandom.base64(n) method in
Ruby 1.9


--=20
I=C3=B1aki Baz Castillo
<>

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: iostream >> string, but fixed length string - how? cpp4ever C++ 2 05-04-2010 10:50 PM
Re: iostream >> string, but fixed length string - how? Victor Bazarov C++ 2 05-03-2010 07:16 AM
How to generate k+1 length strings from a list of k length strings? Girish Sahani Python 17 06-09-2006 11:01 AM
(not really) randon ideas oluoluolu@gmail.com Python 3 03-27-2006 08:49 AM
left(string, length) or right(string, length)? Sam ASP .Net 3 02-17-2005 12:01 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57