I'm creating a method (Pig Latin) and am having trouble with this example test case: translate("eat pie") should return "eatay iepay" but my code doesn't seem to be making the proper changes.
def translate(phrase)
phrase = phrase.split.each do |word|
if ['a', 'e', 'i', 'o', 'u'].include?(word[0])
word = word + 'ay'
else
['a', 'e', 'i', 'o', 'u'].include?(word[1])?
word = word[1..-1] + word[0] + 'ay' : word = word[2..-1] + word[0..1] + 'ay'
end
end
phrase.join(' ')
end
The problem I'm having is that the array enumeration doesn't manipulate each word at all. I'm at a loss for why that is. Thanks in advance.
The each
method simply executes the block for each element of a list. Modifying the control variable word
won't affect the original element of the list.
I suggest you use the map
method, which transforms one list into another. It passes each element of the original list to the block, and replaces it with the value returned by the block.
Also, you should only use the conditional operator a ? b : d
to return a value - you shouldn't modify any variables. So you could write
word = ['a', 'e', 'i', 'o', 'u'].include?(word[1]) ?
word[1..-1] + word[0] + 'ay' :
word[2..-1] + word[0..1] + 'ay'
but here it is best to just use an additional elsif
clause.
This code does what you want.
def translate(phrase)
phrase = phrase.split.map do |word|
if ['a', 'e', 'i', 'o', 'u'].include?(word[0])
word + 'ay'
elsif ['a', 'e', 'i', 'o', 'u'].include?(word[1])
word[1..-1] + word[0] + 'ay'
else
word[2..-1] + word[0..1] + 'ay'
end
end
phrase.join(' ')
end
p translate "eat pie"
output
"eatay iepay"
Update
This is much better written using regular expressions. You may be interested in this variation
def translate(phrase)
phrase.split.map { |word| word.sub /^([^aeiou]*)(.+)/, '\2\1ay' }.join ' '
end
p translate 'pig latin'
output
"igpay atinlay"
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加