Codes316 Codes316 - 1 year ago 86
Ruby Question

Can you replace the character A with T and T with A in Ruby?

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 inputted- the method reverse_it should do the output of GGCAAT.

A is replaced by T, 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
def reverse_it()
puts nucleotide.reverse.gsub("C", "G").gsub("G", "C").gsub("A", "T").gsub("T", "A")

attr_reader :nucleotide
dna1 ="ATTGCC")

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 Source

You are probably looking for tr, so in your method instead of gsub, something like: "ATCG", "TAGC"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download