2012-07-04 31 views
3

我有一個字符串,並希望在不同位置替換多個字符並打印該字符串。Ruby中索引位置的替換字符

E.g.

這裏我喜歡用string_replace替換字符串的位置。

string = "AGACACTTTATATGTAT" 

positions = ["2", "5", "8", "10"] 

string_replace = ["T", "A", "G", "G"] 

我需要的輸出是這樣的=> 「AGTCAATTGAGATGTAT」

我試過,但沒有成功:

positions.zip(string_replace).each do |pos, str| 
    string.gsub!(/#{string}[#{pos}]/, '#{str}') 
    puts string 
end 

任何援助將不勝感激。

回答

6
positions.zip(string_replace).each do |pos, str| 
    string[pos.to_i] = str 
    puts string 
end 
1

這裏:

positions.each_with_index {|o, i| string[o]=replacments[i]}