有一个叫做DNA的课程。一个叫做核苷酸的变量被初始化。在该类中,发现核苷酸的长度,检查两个不同的核苷酸以查看它们是否相等,并显示汉明距离。 “
我的问题是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
问题是Ruby在hamming_distance方法中应用时不接受第二个参数dna2
答案 0 :(得分:2)
如果你想要这个......
dna1.hamming_distance(dna2)
然后,您需要通过访问者方法(@nucleotide
)公开访问attr_reader
,然后只需比较dna1.nucleotide
和dna2.nucleotide
。
hamming_distance
的实施可能如下所示:
def hamming_distance(other_dna)
# compare nucleotide (ours) with other_dna.nucleotide (theirs)
end
答案 1 :(得分: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)