Skip to content

Instantly share code, notes, and snippets.

@markglenfletcher
Created September 6, 2014 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markglenfletcher/77170f6f0ec9bfc5ece5 to your computer and use it in GitHub Desktop.
Save markglenfletcher/77170f6f0ec9bfc5ece5 to your computer and use it in GitHub Desktop.
pig latin
class String
def to_pig_latin
PigLatin.new(self).to_s
end
def self.to_pig_latin(phrase)
phrase.to_pig_latin
end
end
class PigLatin
ALL_LETTERS = [*'a'..'z']
VOWELS = ['a','e','i','o','u']
CONSONANTS = ALL_LETTERS.reject { |letter| VOWELS.include?(letter) }
attr_reader :phrase, :translation
alias :to_s :translation
def initialize(phrase)
@phrase = phrase.downcase
@translation = translate
end
def translate
phrase.split.map do |word|
translate_word word
end.join(' ').chomp
end
private
def translate_word(word)
index = first_vowel_index(word)
case index
when 0
translate_vowel_word word
else
translate_consonant_word word, index
end
end
def first_vowel_index(word)
voewls = word.each_char.map { |char| VOWELS.include?(char) }
voewls.find_index(true) || (word.length)
end
def translate_consonant_word(word, vowel_index)
consonant_cluster = word[0..(vowel_index - 1)]
rest_of_word = word[vowel_index..-1]
rest_of_word << consonant_cluster << 'ay'
end
def translate_vowel_word(word)
word << 'way'
end
end
require 'minitest/autorun'
require_relative 'pig_latin'
class TestPigLatin < Minitest::Spec
describe 'words beginning with a consonant' do
def test_banana
assert_pig_latin_translation 'banana', 'ananabay'
end
end
describe 'words beginning with a consonant cluster' do
def test_glove
assert_pig_latin_translation 'glove', 'oveglay'
end
def test_glove
assert_pig_latin_translation 'drown', 'owndray'
end
end
describe 'words beginning with a vowel' do
def test_egg
assert_pig_latin_translation 'egg', 'eggway'
end
def test_yacht
assert_pig_latin_translation 'yacht', 'achtyay'
end
end
describe 'phrases' do
def test_the_egg_sat_on_the_wall
assert_pig_latin_translation 'humpty dumpty sat on the wall',
'umptyhay umptyday atsay onway ethay allway'
end
end
describe 'string extension' do
def test_translate_word
assert_string_extension 'broken', 'okenbray'
end
def test_translate_phrase
assert_string_extension 'standing on the shoulders of giants',
'andingstay onway ethay ouldersshay ofway iantsgay'
end
def test_class_method
assert_equal 'eetray', String.to_pig_latin('tree')
end
end
private
def assert_pig_latin_translation(phrase, expected)
assert_equal expected, PigLatin.new(phrase).to_s
end
def assert_string_extension(phrase, expected)
assert_equal expected, phrase.to_pig_latin
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment