Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitute character at an index position in Ruby

I have a string and will like to substitute multiple characters on different positions and print that string.

E.g.

Here I like to substitute string at positions with string_replace.

string = "AGACACTTTATATGTAT"

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

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

The output I need is this => "AGTCAATTGAGATGTAT"

I tried this but with no success:

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

Any assistance will be appreciated.

like image 806
Mark Avatar asked Dec 11 '25 09:12

Mark


2 Answers

positions.zip(string_replace).each do |pos, str|
  string[pos.to_i] = str
  puts string
end
like image 173
KL-7 Avatar answered Dec 13 '25 00:12

KL-7


Here:

positions.each_with_index {|o, i| string[o]=replacments[i]}
like image 39
Linuxios Avatar answered Dec 13 '25 00:12

Linuxios