NullRef
NullRef

Reputation: 3743

Ruby: increment all integers in a string by +1

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.

Upvotes: 5

Views: 1604

Answers (3)

ghostdog74
ghostdog74

Reputation: 343171

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"

Upvotes: 5

emboss
emboss

Reputation: 39650

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

Upvotes: 10

Jonathan Allard
Jonathan Allard

Reputation: 19279

The thing with your regex is that it doesn't preserve your original string in the chain in order to put it back. What I did was to split it using spaces, detect which are words or integers using w.to_i != 0 (not counting 0 as an integer, you might want to improve this), add one, and join it back:

s = "1 plus 2 and 10 and 100"

s.split(" ").map{ |e| if (e.to_i != 0) then e.to_i+1 else e end }.join(" ")
=> "2 plus 3 and 11 and 101" 

Upvotes: 0

Related Questions