I am working on a function that translates sentences to pig latin, however when I give the input as something like "cherry", which should give "errychay", it will give "erryay", ONLY if I return newWord + block + 'ay', if I just put it, I will get an array of empty values.
words that start with a vowel work fine obviously (E.G. apple)
def translate(s)
v = %w{a e i o u}
s = s.split.map! do |word|
if v.include? word[0]
word + 'ay'
else
for letter in 0...word.length
block = ''
if !(v.include? word[letter] )
block += word[letter]
else
newWord = word.slice(letter,word.length - 1)
newWord + block + 'ay'
block = ''
break
end
end
end
end
s.join(' ')
end
3 things, the one you identified which is the block = '' needs to happen outside the loop. The other two are:
else
newWord = word.slice(letter,word.length - 1)
newWord + block + 'ay' # this does nothing
block = ''
break # nothing makes it back to map
end
I assume you meant for newWord + block + 'ay'
to be the value returned for the map
call, it's not. Try this:
def translate(s)
v = %w{a e i o u}
s = s.split.map! do |word|
if v.include? word[0]
word + 'ay'
else
block = ''
for letter in 0...word.length
if !(v.include? word[letter] )
block += word[letter]
else
newWord = word.slice(letter,word.length - 1)
newWord += block + 'ay'
block = ''
break(newWord)
end
end
end
end
s.join(' ')
end
p translate('apple')
p translate('cherry')
p translate('fancy')
Running it:
(nick@thin)-(~)
(508)⚡️ ruby Desktop/test.rb
"appleay"
"errychay"
"ancyfay"