# Code exercise in refactoring from a code sample from @brianllamar | |
module DNA | |
module Hamming | |
def self.compute(pair) | |
set_strand_position_by_length(pair) unless pair.same? | |
count_the_distance(pair) | |
end | |
private | |
def self.count_the_distance(pair) | |
pair.entries.map(&:chars).inject(:zip).select{|a,b| a!=b}.count | |
end | |
def self.set_strand_position_by_length(pair) | |
pair.swap! if pair.inject{|a,b|a.length>b.length} | |
end | |
end | |
class Pair < Struct.new(:first, :second) | |
def same? | |
inject(:eql?) | |
end | |
def swap! | |
members.zip(entries.reverse) {|a,b| self[a] = b} | |
end | |
end | |
end | |
dna = lambda {|qty| "ACTG".chars.cycle.take(qty).shuffle.join} | |
pair = DNA::Pair.new(dna[10],dna[12]) | |
puts pair.entries | |
puts DNA::Hamming.compute(pair) |
This comment has been minimized.
This comment has been minimized.
nice use of the lambda and This is really good, it all makes sense and tells a good story of what the purpose of the code is. The only thing I would change is maybe outdent the word |
This comment has been minimized.
This comment has been minimized.
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Code is updated and working as expected. I learned a lot experimenting with Struct and lambda. Strengthened my understanding of zip. Actually had a practical use for it.