Skip to content

Instantly share code, notes, and snippets.

@KevinSia
Last active April 25, 2019 10:22
Show Gist options
  • Save KevinSia/6dd5982bbf2b00581225967f4283e69c to your computer and use it in GitHub Desktop.
Save KevinSia/6dd5982bbf2b00581225967f4283e69c to your computer and use it in GitHub Desktop.
# Fill in the methods below with your solution.
# Do not change the method names
# Iteration 1: Converting one word to Pig Latin
def convert_word_to_pig_latin(word)
if word[0].downcase == 'a' || word[0].downcase == 'e' || word[0].downcase == 'i' || word[0].downcase == 'o' || word[0].downcase == 'u'
word
else
str_front = ''
str_behind = ''
after_vowel = false
word.split('').each do |letter|
if after_vowel
str_front += letter
letter.downcase!
after_vowel = true if letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u'
else
str_behind += letter
end
end
str_front + str_behind + 'ay'
end
end
# def convert_word_to_pig_latin(word)
# vowels = %w(a e i o u)
# if vowels.include?(word[0].downcase)
# word
# else
# str_front = ''
# str_behind = ''
# after_vowel = false
# word.split('').each do |letter|
# if after_vowel
# str_front += letter
# letter.downcase!
# after_vowel = true if vowels.include?(letter)
# else
# str_behind += letter
# end
# end
# str_front + str_behind + 'ay'
# end
# end
# Iteration 2: Converting sentences to Pig Latin
# reuse the above method for each word in the sentence
def convert_sentence_to_pig_latin(sentence)
sentence.split(' ').map{ |w| convert_word_to_pig_latin(w) }.join(" ")
end
p convert_sentence_to_pig_latin('hello world')
# Fill in the methods below with your solution.
# Do not change the method names
# Iteration 1: Converting one word to Pig Latin
def convert_word_to_pig_latin(word)
vowel_index = word =~ /[aeiouAEIOU]/
if vowel_index == 0 || vowel_index == nil
word
else
word[vowel_index..-1] + word[0..vowel_index - 1] + 'ay'
end
end
# Iteration 2: Converting sentences to Pig Latin
def convert_sentence_to_pig_latin(sentence)
sentence.split(' ').map{ |w| convert_word_to_pig_latin(w) }.join(" ")
end
p convert_sentence_to_pig_latin('hello world')
# Fill in the methods below with your solution.
# Do not change the method names
# Iteration 1: Converting one word to Pig Latin
def convert_word_to_pig_latin(word)
word.gsub(/([^aeiouAEIOU]+)([aeiouAEIOU][a-zA-Z]+)/, '\2\1ay')
end
# Iteration 2: Converting sentences to Pig Latin
def convert_sentence_to_pig_latin(sentence)
# sentence.gsub(/(\A|\s)([^aeiouAEIOU]+)([aeiouAEIOU][a-zA-Z]+)/, '\1\3\2ay')
sentence.split(" ").map{|w| convert_word_to_pig_latin(w)}.join(" ")
end
p convert_sentence_to_pig_latin('hello world')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment