Hey there,
A while back I created some code to generate a random number and was wondering if anyone can provide a ore efficient method..
Here is what I Started with...
aStr = "" 11.times { aStr << (rand(9)+1).to_s } [3,7].each { |i| aStr = '-' } aStrHere is the revision I came up with after a little tinkering...
(t=(0..8).inject("") do |r,i| r << ((c="#{(rand(9)+1)}"); c<<"-" if i % 3 == 2; c) end)[0,t.size-1]And finally, here is the masterpiece I came up with (after much brain scratching)
def generate_id (t=(0..2).inject("") { |r,i| r << "#{rand(899)+100}-"})[0,t.size-1]endWhen you run 'generate_id' method, it creates a string of 9 numbers (delimited every 3 with '-').
Obviously, it could easily be modified to generate a longer id and can also easily be changed to an integer value. (by doing something like this)
id_value = generate_idid_value.gsub("-","").to_iAnyway..
Are you guys able to provide an even better method for generating a random id ?
(also - I understand this does not check for any id's already defined - thats already taken care of)
A while back I created some code to generate a random number and was wondering if anyone can provide a ore efficient method..
Here is what I Started with...
aStr = "" 11.times { aStr << (rand(9)+1).to_s } [3,7].each { |i| aStr = '-' } aStrHere is the revision I came up with after a little tinkering...
(t=(0..8).inject("") do |r,i| r << ((c="#{(rand(9)+1)}"); c<<"-" if i % 3 == 2; c) end)[0,t.size-1]And finally, here is the masterpiece I came up with (after much brain scratching)
def generate_id (t=(0..2).inject("") { |r,i| r << "#{rand(899)+100}-"})[0,t.size-1]endWhen you run 'generate_id' method, it creates a string of 9 numbers (delimited every 3 with '-').
Obviously, it could easily be modified to generate a longer id and can also easily be changed to an integer value. (by doing something like this)
id_value = generate_idid_value.gsub("-","").to_iAnyway..
Are you guys able to provide an even better method for generating a random id ?
(also - I understand this does not check for any id's already defined - thats already taken care of)