Codes316 Codes316 - 1 month ago 5
Ruby Question

Why can't I use the same method twice for one instance in ruby?

I have this program that basically uses a method called reverse_complement to reverse a string and replaces some characters with other characters; However, if I use the method twice for the same instance it gives me an undefined error. So, puts dna1.reverse_complement.reverse_complement == dna1.nucleotide should give me a true value. However, it gives an undefined method error.

class DNA
attr_reader :nucleotide

def initialize (nucleotide)
@nucleotide = nucleotide
end
def reverse_complement()
@nucleotide.reverse.tr("ATCG", "TAGC")
end

end
dna1 = DNA.new("ATTGCC")
puts dna1.reverse_complement

puts dna1.nucleotide

puts dna2 = dna1.reverse_complement


puts dna1.reverse_complement.reverse_complement == dna1.nucleotide

Answer

Would something like this suffice?:

class DNA < String
  def reverse_complement
    reverse.tr("ATCG", "TAGC")
  end
end

dna1 = DNA.new("ATTGCC")
puts dna1
# ATTGCC
puts dna1.reverse_complement 
# GGCAAT
puts dna1.reverse_complement.reverse_complement == dna1
# true

Notes

def reverse_complement
  reverse.tr("ATCG", "TAGC")
end

can be written as:

def reverse_complement
  self.reverse.tr("ATCG", "TAGC")
end

where self is the current object. In the examples above, self is dna1 which is an instance of DNA.

Comments