In: Computer Science
RUBY
Write a DNA class that gets initialized with a string of nucleotide characters. An instance of DNA responds to the to_s, length, hamming_distance, contains, positions, and frequencies messages. Where a and b are DNA instances of the same length, the message send a.hamming_distance(b) returns the Hamming distance between a and b. a.contains(b) returns true if b appears as a substring in a, and returns false otherwise. a.positions(n) returns an array of the (zero-based) positions in which the nucleotide n occurs in increasing order. Frequencies returns a hash that maps each of the four nucleotides to the number of times it occurs in the DNA instance.
output:
>> dna1 = DNA.new('ATTGCC') => ATTGCC
>> dna1.length
=> 6
>> puts dna1
ATTGCC
>> dna1.contains('TGC')
true
>> dna1.contains(DNA.new('AT'))
true
>> dna1.contains('GG')
false
>> dna1.positions('T')
[1, 2]
>> dna2 = DNA.new('GTTGAC')
=> GTTGAC
>> dna1.hamming_distance(dna2)
=> 2
>> dna1.hamming_distance(dna1)
=> 0
>> dna1.hamming_distance(DNA.new('AT')) ArgumentError: dnas
of different lengths
from ass2.rb:17:in `hamming_distance' from (irb):8
from C:/Ruby22/bin/irb:11:in '<main>'
>> dna1.frequencies
{"A"=>1, "T"=>2, "G"=>1, "C"=>2}
Copiable code:
class DNA
def initialize(string_dna)
@str_dna=string_dna
end
# method for print
def printdna()
puts @str_dna
end
# method for return
def getstring()
return @str_dna
end
# method for returning the length
def length
puts @str_dna.length
return @str_dna.length
end
#method for computing distance
def hamming_distance(dna2)
#If length not matched, return an error message
if @str_dna.length!=dna2.length
puts "ArgumentError: DNAs of different lengths"
#Compute distance
else
$ival = 0
$numval = dna2.length
$cnt_lo=0
begin
if @str_dna[$ival].chr!= dna2.getstring()[$ival].chr
$cnt_lo+=1
end
$ival +=1
end
while $ival < $numval
puts $cnt_lo
return $cnt_lo
end
end
end
end