Pig Latin

This week I started making this Pig Latin challenge, where I implemented a module and called it into the PigLatin class, this made the code clearer.

We can see the implementation of regular expressions, switch cases, and how to call constants and methods from a module.

Here is the link to the challenge if you want to give it a try: exercise

# Translator module helper for PigLatin class
module Translator
  VOWELS = /(a|e|i|o|u|xr|yt)/
  QU_START = /(^qu)/
  Q_SECOND = /\A.q/
  AY = 'ay'

  def self.vowels(word)
    word + AY
  end

  def self.vowels_nil(word)
    y = word.index('y')
    word[y..] + word[0..y - 1] + AY
  end

  def self.consonants(word)
    case word
    when QU_START
      word[2..] + word[0..1] + AY
    when Q_SECOND
      word[3..] + word[0..2] + AY
    else
      index = word.index(VOWELS)
      word[index..] + word[0..index - 1] + AY
    end
  end
end        
require_relative 'Translator'

# Pig latin class to translate from english to piglatin
class PigLatin
  include Translator
  def self.translate(input_words)
    input_words.split(' ').map do |word|
      if word.start_with?(Translator::VOWELS)
        Translator.vowels(word)
      elsif word.index(Translator::VOWELS).nil?
        Translator.vowels_nil(word)
      else
        Translator.consonants(word)
      end
    end.join(' ')
  end
end        

要查看或添加评论,请登录

Danys Linares的更多文章

  • Show Testing skills

    Show Testing skills

    A long time ago, I saw a challenge from a Junior interview. Before you even get to this challenge, you must go through…

  • Ruby: twofer

    Ruby: twofer

    I will show how to approach the problem more than solving a challenge, this will give a methodology to apply when…

  • Complex numbers Challenge

    Complex numbers Challenge

    I completed this challenge on Exercism; it is an easy level, but it doesn't mean it's not worthwhile. You can discover…

社区洞察

其他会员也浏览了