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

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”

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

On 5/12/06, Alex Y. [email protected] 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.

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

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.

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

On 5/12/06, C Erler [email protected] wrote:

Quite right. My regex should have been anchored:

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

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

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

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