Codes316 Codes316 - 2 months ago 14
Ruby Question

How to replace the character A with T and T with A

I'm trying to create a program that will take a string and reverse it and replace it with its complimentary characters.

For example, if the string "ATTGCC" is input, the method

reverse_it
should output "GGCAAT".

"A" is replaced by "T", and "T" is replaced by "A". "C" is replaced by "G", and "G" is replaced by "C".

This is my code:

class DNA
def initialize (nucleotide)
@nucleotide = nucleotide
end
def reverse_it()
puts nucleotide.reverse.gsub("C", "G").gsub("G", "C").gsub("A", "T").gsub("T", "A")
end
protected

attr_reader :nucleotide
end
dna1 = DNA.new("ATTGCC")
dna1.reverse_it


The problem is
gsub
replaces all occurrences of the character and
sub
replaces only the first instance of the character in the string. Is there a built-in method to make this program work?

Answer

You are probably looking for tr, so in your method instead of gsub, something like:

nucleotide.reverse.tr "ATCG", "TAGC"