Is there a method for incrementing string names?!?


#1

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

#2

Human D. wrote:

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?
Nearly…
irb(main):001:0> s = “aaa”
=> “aaa”
irb(main):002:0> s = s.succ
=> “aab”
irb(main):003:0> s = s.succ
=> “aac”

Or…

irb(main):001:0> s = “aaa1”
=> “aaa1”
irb(main):002:0> s = s.succ
=> “aaa2”
irb(main):003:0> s = s.succ
=> “aaa3”


#3

Alex Y. wrote:

irb(main):003:0> s = s.succ
=> “aaa3”

Note the “aaa9”.succ => “aab1”

So if you only want the number incremented be sure to append
enough 0s


#4

On 5/12/06, Alex Y. removed_email_address@domain.invalid wrote:

irb(main):001:0> s = “aaa1”
=> “aaa1”
irb(main):002:0> s = s.succ
=> “aaa2”
irb(main):003:0> s = s.succ
=> “aaa3”

But don’t forget:

irb(main):001:0> ‘aa9’.succ
=> “ab0”

So it won’t do what’s needed.

Cheers,

Pedro.


#5

Why not just create an array called name and access with the numbers?

irb(main):003:0> name << ‘charlie’ << ‘moir’ << ‘bowman’
=> [“charlie”, “moir”, “bowman”]
irb(main):006:0> puts name[0]
charlie
=> nil
irb(main):007:0> puts name[1]
moir
=> nil
irb(main):008:0> puts name[2]
bowman
=> nil

Charlie B.
http://www.recentrambles.com


#6

agrees

How about something like this?

def next_name(s)
  s.reverse =~ /(\d*)(.*)/
  digits_r, word_r = $~[1,2]
  digits = digits_r ? digits_r.reverse.to_i : 0
  digits += 1
  word_r.reverse + digits.to_s
end

next_name "var"      # => "var1"
next_name "var32" # => "var33"
next_name "var99" # => "var100"

String.succ will blow up for cases 1 and 3.


#7

Here’s a method to do it :

def inc name
parts = name.scan(/^(.*\D)(\d+)$/).first
if parts.nil?
“#{name}1”
else
“#{parts.first}#{parts.last.to_i + 1}”
end
end


#8

On 5/12/06, C Erler removed_email_address@domain.invalid wrote:

Quite right. My regex should have been anchored:

/\A(\d*)(.*)/


#9

Once again, I come up with something better two minutes after I hit
send.

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


#10

My friends ask me why you love Ruby! that’s becasue of you guys. ; )
Thanks