Last active
August 29, 2015 14:07
-
-
Save danielpclark/c414a3e0dd9a7df767b6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
nice use of the lambda and 👍 for keeping the methods short and to the point.
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 private
private
is not a block and therefore indentation doesn't apply. It, by itself, modifies any methods below to private methods. It can also be used inline for just one method private def my_private_method
. It's a modifier for methods... you also have public
which you can use in the same manner.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.