Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

How to compare two instance variables from the same class in Ruby?

There is a class called DNA. a variable called nucleotide gets initialized. In the class the length of the nucleotide is found, two different nucleotides are checked to see if they are equal, and the hamming distance is displayed. '

My problem is Ruby only interprets one instance of nucleotide. How do I compare nucleotide to other nucleotides that get created?

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)

An example of how I'm trying to make the program work:

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

The problem is Ruby does not accept the second parameter dna2 when applied in the hamming_distance method

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to make nucleotide an accessible field. In this example, I've made it protected, but you could make it public.

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

Then use it like:

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

one.hamming_distance(two)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...