Is there a method for incrementing string names?!?

Hello,
I have model which has a property named “name”, I want to append a
number to the end of the name when there is similar name in db.

name, name1, name2…

Is there a ready to use method in ruby and/or rails for doing so?

Thanks in advance,

  • Dunnil

Check out String#next

I found my answer on the ruby-talk by C Erler [1]:

class String
def inc
parts =3D scan(/^(.*\D)?(\d+)?$/).first
“#{parts.first}#{parts.last.to_i + 1}”
end
end

[1] http://www.ruby-talk.org/cgi-bin/scat.rb/ruby/ruby-talk/192523

Human D. wrote:

On 5/12/06, Daniel B.
[email protected] wrote:

Check out String#next

Why didn’t you like Daniel’s answer?

irb(main):003:0> a = “name1”
=> “name1”
irb(main):004:0> a.next
=> “name2”
irb(main):005:0> a.next.next
=> “name3”

It seems to be exactly what you were asking for.

Ray

Ezra Z. wrote:

That way it falls on its face when you go above number nine.

ez webrate $ irb
irb(main):001:0> a = ‘name9’
=> “name9”
irb(main):002:0> a.next
=> “namf0”

Hah! Ruby has surprised me.

Here are three more good ones:

irb(main):012:0> a = “name-9”
=> “name-9”
irb(main):013:0> a.next
=> “namf-0”
irb(main):014:0> a = “name-”
=> “name-”
irb(main):015:0> a.next
=> “namf-”
irb(main):018:0> a = “----”
=> “----”
irb(main):019:0> a.next
=> “—.”

Thanks, I’ll be careful with next.

Ray

On May 12, 2006, at 3:55 PM, Ray B. wrote:

Check out String#next
It seems to be exactly what you were asking for.

Ray

That way it falls on its face when you go above number nine.

ez webrate $ irb
irb(main):001:0> a = ‘name9’
=> “name9”
irb(main):002:0> a.next
=> “namf0”

-Ezra