ruby - Why is my while loop getting stuck? Did I forget a step? -
i'm still working way through exercises , i'm sure isn't first time question has been brought on stack... interested in pursuing question in way interpret write code love figuring out how make approach work.
it's pig latin 1 :) basically. if put in word variable... or 2 words, should translate words called pig latin. pig latin takes word hello , changes ellohay. in pig latin, words have begin vowel. can have word "closed" , should "osedclay". i've decided approach while loop. while rspec check works first 2 checks... seems stuck in infinite loop when starts checking third word (which happens "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
!= operator doesn't work way think does.
while separated[0] !=("a" || "e" || "i" || "o" || "u") the line above equivalent to
while separated[0] != 'a' if there's no "a" in word, loop infinite. should rewrite condition
while !'aeiou'.include?(separated[0]) i know, i'll use regular expressions...
here's shorter version of method
def translate(word) # 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"
Comments
Post a Comment