Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: increment all integers in a string by +1

Tags:

string

regex

ruby

I am looking for a succinct way to increment all the integers found in a string by +1 and return the full string.

For example:

"1 plus 2 and 10 and 100"

needs to become

"2 plus 3 and 11 and 101"

I can find all the integers very easily with

"1 plus 2 and 10 and 100".scan(/\d+/)

but I'm stuck at this point trying to increment and put the parts back together.

Thanks in advance.

like image 741
NullRef Avatar asked Aug 31 '11 03:08

NullRef


2 Answers

You could use the block form of String#gsub:

str = "1 plus 2 and 10 and 100".gsub(/\d+/) do |match|
  match.to_i + 1
end

puts str

Output:

2 plus 3 and 11 and 101
like image 81
emboss Avatar answered Nov 03 '22 01:11

emboss


The gsub method can take in a block, so you can do this

>> "1 plus 2 and 10 and 100".gsub(/\d+/){|x|x.to_i+1}
=> "2 plus 3 and 11 and 101"
like image 32
ghostdog74 Avatar answered Nov 03 '22 01:11

ghostdog74