Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# 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)
@danielpclark

This comment has been minimized.

Copy link
Owner Author

@danielpclark danielpclark commented Oct 6, 2014

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.

@bdougie

This comment has been minimized.

Copy link

@bdougie bdougie commented Oct 6, 2014

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

@danielpclark

This comment has been minimized.

Copy link
Owner Author

@danielpclark danielpclark commented Oct 6, 2014

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