user5603796
user5603796

Reputation: 389

Increment alphabetical string in Ruby

I need to increment an alphabetical string in Ruby.

The string format is

A clients unique ID. This is six characters long and must be in the form [A-Z][A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9]. The numbers [0-9] at the beginning of an ID are legal characters, but reserved for future use.

The next string after AAAAAA is AAAAAB. Once AAAAAZ is reached the next string is AAAABA and so on.

What is the simplest method to generate these strings in Ruby?

I will be storing the last user ID in a variable for example lastUID = AAAAAA.

Upvotes: 0

Views: 298

Answers (2)

7urkm3n
7urkm3n

Reputation: 6311

Example:

lastUID = "A" * 6

100.times do |i|
  lastUID = lastUID.next
end

Upvotes: 1

tadman
tadman

Reputation: 211590

It's pretty simple:

"AAAAAA".succ
# => "AAAAAB"
"AAAAAZ".succ
# => "AAAABA"

Upvotes: 5

Related Questions