2016-09-26 42 views
-1

有一類叫做DNA。稱爲核苷酸的變量被初始化。在該類中找到核苷酸的長度,檢查兩個不同的核苷酸以查看它們是否相等,並顯示漢明距離。 '如何比較來自Ruby中同一類的兩個實例變量?

我的問題是Ruby僅解釋核苷酸的一個實例。我如何將核苷酸與創建的其他核苷酸進行比較?

class DNA 
    def initialize (nucleotide) 
    @nucleotide = nucleotide 
    end 
    def length 
    @nucleotide.length 
    end 
    def hamming_distance 
    puts @nucleotide == @nucleotide 
    end 
end 

dna1 = DNA.new("ATTGCC") 
dna2 = DNA.new("GTTGAC") 
puts dna1.length 
    puts dna2.length 

puts dna1.hamming_distance(dna2) 

的我如何努力使工作方案的一個例子:

dna1 = DNA.new('ATTGCC') 
=> ATTGCC 
>> dna1.length 
=> 6 
>> dna2 = DNA.new('GTTGAC') 
=> GTTGAC 
>> dna1.hamming_distance(dna2) 
=> 2 
>> dna1.hamming_distance(dna1) 
=> 0 

問題是紅寶石當hamming_distance方法應用於不接受第二個參數DNA2

回答

2

你需要做的核苷酸訪問場。在這個例子中,我已經保護了它,但是你可以公開它。

class DNA 
    def initialize(nucleotide) 
    @nucleotide = nucleotide 
    end 

    def length 
    @nucleotide.length 
    end 

    def hamming_distance(other) 
    self.nucleotide #=> this nucleotide 
    other.nucleotide #=> incoming nucleotide 
    end 

    protected 

    attr_reader :nucleotide 
end 

然後使用它像:

one = DNA.new("ATTGCC") 
two = DNA.new("GTTGAC") 

one.hamming_distance(two) 
2

如果你想這個工作...

dna1.hamming_distance(dna2) 

然後,你需要使@nucleotide通過訪問方法(attr_reader)公開訪問,然後簡單比較dna1.nucleotidedna2.nucleotide

你實現hamming_distance可能是這樣的:

def hamming_distance(other_dna) 
    # compare nucleotide (ours) with other_dna.nucleotide (theirs) 
end