Techniques to avoid duplication on ruby code


I’m doing the ruby trail and trying to create the cleaner code I can. I often try to create different classes for any “concepts” that I see, but this frequently leads to code duplication.

Let me show an example. Here I’m trying to solve the Poker Winner Hand problem. I write one class for each possible play (full house, straight, etc.) and each class has two specific methods: the spaceship operator (<=>) and a self.match? that answers if a given set of cards match with that specific play.

class Straight
  def self.match?(hand)
    # Checks if this hand is a sequence
  def <=>(hand)
    # Figure out which hand is the better

As you may be wondering, the straight class checks for the higher card, the second high card, and so forth to break a tie, and so do the flush class. The same duplication happen with the pair, trips and quads games.

I’m trying to remove the duplications here, but when I extract methods, create super classes or anything else, it seems that the code become less clear. Right now I can just read the Straight class and see what it does. The same happens to the Flush class, even though the code looks alike. Any thoughts?

The critical thing is to use good names. If you name a method well, then you shouldn’t need to look at its implementation to know what its does.