Search code examples
rubystringrspecwhile-loopinfinite

Why is my while loop getting stuck? Did I forget a step?


I'm still working my way through some exercises and I'm sure this isn't the first time this question has been brought up on stack... but I am interested in pursuing this question in the way that I would interpret to write the code so I would love some help figuring out how to make my approach work.

It's the pig latin one :) Basically. If you put in a word into the variable... or two words, it should translate those words into what is called pig latin. Pig latin takes a word like hello and changes it to ellohay. In pig latin, the words have to begin with a vowel. So you can even have the word "closed" and it should say "osedclay". I've decided to approach this with a while loop. While my rspec check works with the first two checks... it seems to get stuck in an infinite loop when it starts checking the third word (which happens to be "cherry")

Thoughts anyone?

def translate(word)
separated = word.split("")
while separated[0] !=("a" || "e" || "i" || "o" || "u")
    letter = separated.shift
    separated << letter
    separated
end
    word = separated.join("")
    word + "ay"
end

Solution

  • != operator doesn't work the way you think it does.

    while separated[0] !=("a" || "e" || "i" || "o" || "u")
    

    The line above is equivalent to

    while separated[0] != 'a'
    

    If there's no "a" in your word, loop is infinite. You should rewrite your condition

    while !'aeiou'.include?(separated[0])
    

    I know, I'll use regular expressions...

    Here's somewhat shorter version of the method

    def translate(word)
      # you can make one-liner out of it.
      leading_consonants_regex = /^([bcdfghjklmnpqrstvwxyz]+)(.*)/
      word.sub(leading_consonants_regex, '\\2\\1ay')
    end
    
    translate('sheep') # => "eepshay"
    translate('dog') # => "ogday"
    translate('closed') # => "osedclay"
    translate('cherry') # => "errychay"