Search code examples
randomuuidsmalltalk

Generate random strings to append to UID


I prefer to generate uniquely random alpha-numeric string to append to the end of my UID.

The closest I could find in the class library so far has been the Random class, which generates numbers which is the next best thing.

What I have so far is:

getNextRandomNumber
^(((rand nextValue) / 
   (Time now milliSeconds asInteger / Time now minutes asInteger 
   + (Time now hour24 asInteger)) asInteger)).

rand is a class variable, initialized as:

initialize
    rand := Random new.

This seems very poorly written. But I'm unsure of what else to do.


Solution

  • Which dialect are you using?

    In Pharo, I usually implement a method in String class called something like #randomOfSize:. Something like:

    String class >> randomOfSize: anInteger
    
    ^ self streamContents: [ :s | 
        anInteger timesRepeat: 
          [ s nextPut: (Character codePoint: (97 to: 122) atRandom) ] ]
    

    You can tweak the character codes to get the interval of characters you need.

    Then, to generate an 8 characters long random string you can do:

    String randomOfSize: 8
    

    In Pharo, you can also use the UUID class, as follows:

    UUID new printString
    

    Hope it helped!