Forum: Ruby on Rails Is there a method for incrementing string names?!?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7595ff5e64d9a309c29932d106959973?d=identicon&s=25 Human Dunnil (Guest)
on 2006-05-12 15:51
(Received via mailing list)
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
16b26104470ae1b64958f3caa836c193?d=identicon&s=25 Danny Burkes (dburkes)
on 2006-05-12 17:07
Check out String#next
7595ff5e64d9a309c29932d106959973?d=identicon&s=25 Human Dunnil (Guest)
on 2006-05-12 18:04
(Received via mailing list)
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...
E28c35323f624b8b9ed8712e25105454?d=identicon&s=25 Ray Baxter (Guest)
on 2006-05-13 00:58
(Received via mailing list)
Human Dunnil wrote:
>
>
> On 5/12/06, Daniel Burkes
> <dburkes@netable.com> 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
6076c22b65b36f5d75c30bdcfb2fda85?d=identicon&s=25 Ezra Zygmuntowicz (Guest)
on 2006-05-13 01:04
(Received via mailing list)
On May 12, 2006, at 3:55 PM, Ray Baxter 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
E28c35323f624b8b9ed8712e25105454?d=identicon&s=25 Ray Baxter (Guest)
on 2006-05-13 01:36
(Received via mailing list)
Ezra Zygmuntowicz 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
This topic is locked and can not be replied to.