4

I am writing a ruby uid generator and i need to generate unique ids in incremental order. The unique ids are strings that vary from 3 to 9 characters.

What i want to achieve is this:

Get the last generated identifier, convert it to bits, and 1 bit to it(basically do a + 1) and convert the result back to ascii. This way i can prevent a unique id from being generated twice.

How can i do this in ruby. I am aware of #pack and #unpack methods but i can't figure out a way.

1
  • Could you give an example? Commented Jul 25, 2014 at 5:14

1 Answer 1

3

You can use something like this:

a = "Foobar".unpack("B*")[0].to_i(2)+1

=> 77444424032627

["0" + a.to_s(2)].pack("B*")

=> "Foobas"

Sign up to request clarification or add additional context in comments.

4 Comments

that's equivalent to "Foobar".succ
So what I need is this: I have a set of characters [0-9A-Z], su numbers and only uppercase letters. I want to be able to start from 000 and go up to ZZZZZZZZZ(9 Zs) just by changing the last bit without choosing randomly. Is that possible in ruby?
Do you want all the permutations? Use then: a = (0..9).to_a + ("A".."Z").to_a a.permutation(3).to_a
Or if you want a function that based on a uid then generates the successor uid, then you should use succ and some logic in your function for detecting changes for numbers and chars. Explore this code: a = "0A"; (1..(10**2)).each do |m|; puts a; a.succ!; end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.