开发者

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开发者_如何学Python+/)

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

Thanks in advance.


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


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"


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" 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜