So I wrote this code:
def translate_word word
vowel = ["a", "e", "i", "o", "u"]
if vowel.include? word[0]
word = word + "ay"
elsif vowel.include? word[1]
word = word[1..-1] + word[0] + "ay"
else
word = word[2..-1] + word[0..1] + "ay"
end
end
Translates a word into pig latin. For my purposes, works great. But what if we want to translate more than one word?
def translate string
vowel = ["a", "e", "i", "o", "u"]
words = string.split(" ")
words.each do |word|
if vowel.include? word[0]
word = word + "ay"
elsif vowel.include? word[1]
word = word[1..-1] + word[0] + "ay"
else
word = word[2..-1] + word[0..1] + "ay"
end
end
words.join(" ")
end
Except, if we try to do this with one word, it'll notice there aren't any spaces, say screw that, and return a string. Won't even throw me an error when I try to .each it, but the .each won't do any thing.
puts "apple".split
#=>apple
puts translate "apple"
#=>apple
This isn't an insurmountable problem. I could just run string.includes? " " and then run the two slightly different programs depending on if it was there or not. But this seems very ineloquent. What would be a better or more idiomatic way to deal with the string and the loop?