2013-09-01 57 views
0

我知道在ruby中可以使用gsub和正則表達式來搜索和替換字符串。將表達式應用到ruby搜索並用正則表達式替換

但是,在替換之前,可以將表達式應用於搜索結果並進行替換。

例如在下面的代碼,雖然你可以使用匹配的字符串\0你不能表達適用於它(如\0.to_i * 10)和這樣一個錯誤的結果:

shopping_list = <<LIST 
3 apples 
500g flour 
1 ham 
LIST 

new_list = shopping_list.gsub(/\d+/m, \0.to_i * 10) 
puts new_list #syntax error, unexpected $undefined 

它似乎只與工作字符串文字:

shopping_list = <<LIST 
3 apples 
500g flour 
1 ham 
LIST 

new_list = shopping_list.gsub(/\d+/m, '\0 string and replace') 
puts new_list 

回答

1

這是你想要的嗎?

shopping_list = <<LIST 
3 apples 
500g flour 
1 ham 
LIST 

new_list = shopping_list.gsub(/\d+/m) do |m| 
    m.to_i * 10 
end 

puts new_list 
# >> 30 apples 
# >> 5000g flour 
# >> 10 ham 

文檔:String#gsub

+0

是的!謝謝,但(我對Ruby很新)你怎麼知道一個方法是否會阻塞? – user2521439

+0

@ user2521439:你閱讀文檔或源代碼:) –