4

Is there some ready-made algorithm to generate invitation code by ruby? I can think at first MD5, but its output is too long for 32, so I want the output length is less than 16.

Thank you in advance.

miku
  • 181,842
  • 47
  • 306
  • 310
ywenbo
  • 3,051
  • 6
  • 31
  • 46
  • `(0...16).map{65.+(rand(25)).chr}.join` – miku Jun 13 '11 at 12:18
  • @miku thank you, but i think the way you suggested is maybe too much collision. – ywenbo Jun 13 '11 at 12:23
  • too much collision? How many invites are you going to send? Not very *quantitative*, but 23283064365386962890625 possible invitation codes should get you *a long way* before any collision. – miku Jun 13 '11 at 12:24
  • @miku we're ready to send out 10 thousand invitation code. i knew your meaning, i just think rand(25), since its seed is only 25 even though its length is 16. – ywenbo Jun 13 '11 at 12:26

3 Answers3

3

Assuming you are storing the code (otherwise, what's the point?) just make a random string, and check to see if it exists before saving, and try a new string if it does. No major algorithm needed.

DGM
  • 26,629
  • 7
  • 58
  • 79
0
SecureRandom.uuid

This will produce out put like the following.

2.1.0 :005 > SecureRandom.uuid
 => "b2a8ed4c-f71f-4c7d-a0fb-a66de58d37cc" 
2.1.0 :006 > 

Short enough and extremely unlikely to cause a collision.

Ian Purton
  • 15,331
  • 2
  • 27
  • 26
  • A uuid is 16 bytes. The OP complainted about MD5 being too long at 32 hex digits and asks for 16 characters. Your encoded uuid consists of 36 characters. So "Short enough" is a dubious claim. – CodesInChaos Jun 19 '14 at 16:06
0

How "secure" do you want your invitation code? You could generate an MD5 hash and simply take the first or last 16 characters, or any 16-character combination from the hash code (e.g. every other position in the hash). That should be good enough for an invitation-code.

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194