Ruby:将字符串中的所有整数递增+1

Nul*_*Ref 5 ruby regex string

我正在寻找一种简洁的方法来将字符串中的所有整数递增+1并返回完整的字符串.

例如:

"1 plus 2 and 10 and 100"
Run Code Online (Sandbox Code Playgroud)

需要成为

"2 plus 3 and 11 and 101"
Run Code Online (Sandbox Code Playgroud)

我可以很容易地找到所有整数

"1 plus 2 and 10 and 100".scan(/\d+/)
Run Code Online (Sandbox Code Playgroud)

但是我在这一点上陷入困​​境,试图增加并将部件重新组合在一起.

提前致谢.

emb*_*oss 10

您可以使用String#gsub块形式:

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

puts str
Run Code Online (Sandbox Code Playgroud)

输出:

2 plus 3 and 11 and 101
Run Code Online (Sandbox Code Playgroud)


gho*_*g74 5

gsub方法可以采用块,因此您可以执行此操作

>> "1 plus 2 and 10 and 100".gsub(/\d+/){|x|x.to_i+1}
=> "2 plus 3 and 11 and 101"
Run Code Online (Sandbox Code Playgroud)