2011-08-31 82 views
5

我正在寻找一种简洁的方式来将所有在字符串中找到的整数加1并返回完整的字符串。Ruby:将字符串中的所有整数加1 +1

例如:

"1 plus 2 and 10 and 100" 

需求,成为

"2 plus 3 and 11 and 101" 

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

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

但我被困在这一点上试图增加并重新放回零件。

在此先感谢。

回答

10

你可以使用block form of String#gsub

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

puts str 

输出:

2 plus 3 and 11 and 101 
+0

甜!我知道有一个超级简单的方法来做到这一点。谢谢! – NullRef

+1

这很酷。不知道gsub占用了块。 – jergason

0

与你的正则表达式的东西是,它不会保留链中的原始字符串以便将其放回。我所做的是使用空格分割它,发现它是用w.to_i != 0单词或整数(不包括0的整数,你可能想改善这一点),增加一个,并加入回:

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

gsub方法可以在块,这样你就可以做到这一点

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