gpt4 book ai didi

"pig latin"的 Ruby 映射函数

转载 作者:数据小太阳 更新时间:2023-10-29 08:31:00 24 4
gpt4 key购买 nike

我正在尝试编写一个 ruby​​ 函数,该函数接收一串单词并将其转换为 Pig Latin 。我将字符串分解成一个数组,并尝试遍历每个元素。当输入“eat pie”时,结果是“eat ie”,但我不确定为什么。

string = "eat pie"    
array = string.split(" ")

array.map do |word|

if word[0].chr == "a" || word[0].chr == "e" || word[0].chr == "i" || word[0].chr == "o" || word[0].chr == "u"

word = word + "ay"

elsif word[1].chr == "a" || word[1].chr == "i" || word[1].chr == "o" || word[1].chr == "u"
temp = word[0]
word[0] = ""
word = word + temp
word = word + "ay"

elsif word[2].chr == "a" || word[2].chr == "i" || word[2].chr == "o" || word[2].chr == "u"
temp = word[0] + word[1]
word[0] = ""
word[0] = ""
word = word + temp
word = word + "ay"

else ## three consonants
temp = word[0] + word[1] + word[2]
word[0] = ""
word[0] = ""
word[0] = ""
word = word + temp
word = word + "ay"

end ## end of if statement

end ## end of iteration

puts array.join(" ")

最佳答案

同意提供的其他答案,这里是您的代码的一个稍微不那么冗长的版本,以防它对您有所帮助。

input = 'pig latin is awesome'

arr = input.split(' ').map do |wrd|
if %w(a e i o u).include? wrd[0]
wrd + 'ay'
elsif %w(a i o u).include? wrd[1]
wrd[1..-1] + wrd[0] + 'ay'
elsif %w(a i o u).include? wrd[2]
wrd[2..-1] + wrd[0] + wrd[1] + 'ay'
else
wrd[3..-1] + wrd[0] + wrd[1] + wrd[2] + 'ay'
end
end.join(' ')

puts arr

关于 "pig latin"的 Ruby 映射函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34620321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com