App Academy

Intro to programing - Question about the Pig Latin Word problem

I’m in the intro to programing course, and I have a question in the problem of the ‘pig latin word’ the code is below. In the second part of the code, where we look to find the first vower of the word, how come the if returns the data of the first vowel only and it doesn’t keep going through the next letters until it finds the next vowel? in the other problems whenever we use if, the whole word/array is reviewed, but here in the first vowel it ends.

def pig_latin_word(word)
vowels = “aeiou”

if vowels.include?(word[0])
return word + “yay”

#This is the part I’m talking about
word.each_char.with_index do |char, i|
if vowels.include?(char)
return word[i…-1] + word[0…i] + “ay”

puts pig_latin_word(“apple”) # => “appleyay”
puts pig_latin_word(“eat”) # => “eatyay”
puts pig_latin_word(“banana”) # => “ananabay”
puts pig_latin_word(“trash”) # => “ashtray”

This is a great question, and shows that you understand how the .each_char method works, with a conditional inside.

In this case, the reason that all characters are not checked is because the code is using the return keyword inside the conditional. Whenever a line of code is run and it hits a return keyword it will immediately return that value, which breaks it out of the entire method.

So in this example, once you hit the first character that is a vowel, you hit the return and the method ends. If you had assigned a value to a variable instead of using the return keyword inside the conditional, you would continue iterating through the characters as expected, but you would continue reassigning that variable each time the condition evaluates to true…but that would not get you the output you need for pig latin.

Try it out and see what happens!