Pig Latin
Danys Linares
Full Stack Web Developer | In love with JavaScript, Rails, React, and Redux | A proactive and communicative person | Have you an idea? Let's make it real!
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