Sunday, April 3, 2016

Learnings from solving the Hamming exercise on Exercism

Hamming Exercise

  • Learnt how to use count with each_with_index
    • This helped me do away with the temp variable distance that I had used as a counter.

Before - Uses a temp variable called distance as a counter

class Hamming
  VERSION = 1

  def self.compute(dna_strand_1, dna_strand_2)
    raise ArgumentError if dna_strand_1.length != dna_strand_2.length
    distance = 0
    dna_strand_1.chars.each_with_index do |strand_1_char, index|
      distance += 1 unless strand_1_char == dna_strand_2[index]
    end
    distance
  end
end

After - Uses count insead of distance . Taken from rwz's solution.

class Hamming
  VERSION = 1

  def self.compute(dna_strand_1, dna_strand_2)
    raise ArgumentError if dna_strand_1.length != dna_strand_2.length

    dna_strand_1.chars.each_with_index.count do |strand_1_char, index|
       strand_1_char != dna_strand_2[index]
    end
  end
end
  • Looking back at this new approach I could relate better to the Nitpick made in my solution by rikki - the friendly neighborhood code review robot, who said -

Whenever you are looping through a collection and find yourself writing a conditional (if or unless) nested inside of the loop, take a moment to look through the available enumerable methods. There are some very handy ones that might let you simplify.

Misc Learnings

  • Use chars to get an array of characters from a string
  • Use zip to merge corresponding elements of two or more arrays as used wrt henrik's solution. Sample usage -
2.3.0 :008 > b = [7, 9]
2.3.0 :009 > c = [4, 8]
2.3.0 :010 > a = [2, 3]
 => [2, 3]
2.3.0 :011 > a.zip(b)
 => [[2, 7], [3, 9]]
2.3.0 :012 > a.zip(b,c)
 => [[2, 7, 4], [3, 9, 8]]
2.3.0 :013 >
  • Learnt that one needn't have to use a class always(using a class was the first thing that came to my mind when solving this). A module could also be used to solve this. The reasoning behind this(mentioned below) is something I hadn't thought of earlier. It also kinda makes sense to me becuase with Modules one cannot create instances of it and if there isn't a need to create instances, then why not consider using a module. People may want to debate further on this(i.e., on using classes vs modules - that's beyond the scope of this post) but the below point in itself was something worth reflecting upon for me.

    Yeah, there's not much reason to use a class for this, since there are no instances involved over here.

  • Something similar was also mentioned in markijbema's solution.

Lastly, my learnings here wouldn't have been possible without those who've contributed to exercism and to those whose solution I had an opportunity to refer to. I'm thankful to them.

No comments:

Post a Comment