Most efficient way to "increment" a string?

I have members with usernames. In the event that a new member requests
an already-existing username, I’d like to automatically “increment” a
next-best string:

johnny
johnny1
johnny2

Knowing RoR, my gut tells me there’s some elegant, concise way to do
this, but I can’t think of it. Any advice?

On 7/11/06, Max R. [email protected] wrote:

I have members with usernames. In the event that a new member requests
an already-existing username, I’d like to automatically “increment” a
next-best string:

johnny
johnny1
johnny2

Knowing RoR, my gut tells me there’s some elegant, concise way to do
this, but I can’t think of it. Any advice?

String#succ

From:
http://www.ruby-doc.org/core/

http://www.ruby-doc.org/core/classes/String.html#M001851

  • Rob

http://www.robsanheim.com
http://www.seekingalpha.com
http://www.ajaxian.com

On Wednesday, July 12, 2006, at 4:46 AM, Max R. wrote:


Posted via http://www.ruby-forum.com/.


Rails mailing list
[email protected]in.invalid
http://lists.rubyonrails.org/mailman/listinfo/rails

Actually, It’s a ruby thing.

“johnny1”.succ => “johnny2”

but watch out, it has some quirks.

“johnny”.succ => “johnnz”
“johnny9”.succ => “johnnz0”

_Kevin

but watch out, it has some quirks.

“johnny”.succ => “johnnz”
“johnny9”.succ => “johnnz0”

What about String#sub(/(\d*)\Z/)?

“jonny”.sub(/(\d*)\Z/){ $1.to_i.succ } # => “jonny1”
“jonny1”.sub(/(\d*)\Z/){ $1.to_i.succ } # => “jonny2”
“jonny9”.sub(/(\d*)\Z/){ $1.to_i.succ } # => “jonny10”


Yugui
[email protected]
http://idm.s9.xrea.com

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs