Generate randon string of fixed length (in bytes)

Discussion in 'Ruby' started by Iñaki Baz Castillo, Jan 27, 2011.

  1. 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
    <>
    Iñaki Baz Castillo, Jan 27, 2011
    #1
    1. Advertising

  2. 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
    <>
    Iñaki Baz Castillo, Jan 27, 2011
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Sam
    Replies:
    3
    Views:
    14,091
    Karl Seguin
    Feb 17, 2005
  2. Replies:
    3
    Views:
    250
    Tim Roberts
    Mar 27, 2006
  3. Girish Sahani
    Replies:
    17
    Views:
    571
    Boris Borcic
    Jun 9, 2006
  4. Victor Bazarov
    Replies:
    2
    Views:
    699
    Alf P. Steinbach
    May 3, 2010
  5. cpp4ever
    Replies:
    2
    Views:
    886
    cpp4ever
    May 4, 2010
Loading...

Share This Page