Pig Latin
规则1:如果单词以元音开头,请添加“ay”声音 这个词的结尾。
规则2:如果一个单词以辅音开头,请将其移至最后 单词,然后在单词的末尾添加“ay”声音。
以下程序适用于ruby。但我对如何使用“地图”功能感到困惑?请参阅以下代码:
def translate(sentence)
if sentence.include?(" ")
words = sentence.split(" ").map do |word|
translate_word(word)
end
return words.join(" ")
else single_word = sentence
translate_word(single_word)
end
end
以上句子有效!但如果我使用:
words = sentence.split(" ")
words.map do |word|
translate_word(word)
end
它不起作用!为什么?我以为他们是一样的......
def translate_word(w)
vowels = %w[a e i o u]
consonants = ("a".."z").to_a - vowels
if vowels.include?(w[0])
w + "ay"
elsif consonants.include?(w[0]) && vowels.include?(w[1]) && w[1] != "u"
w[1..-1] + w[0] + "ay"
elsif (consonants.include?(w[0]) && consonants.include?(w[1]) && vowels.include?(w[2]) && w[2] != "u") || (w[0] == "q" && w[1] == "u")
w[2..-1] + w[0..1] + "ay"
elsif (consonants.include?(w[0]) && consonants.include?(w[1]) && consonants.include?(w[2]) && vowels.include?(w[3]))
w[3..-1] + w[0..2] + "ay"
elsif consonants.include?(w[0]) && w[1] == "q" && w[2] == "u"
w[3..-1] + w[0..2] + "ay"
end
end
答案 0 :(得分:2)
#map
函数返回一个你要解雇的新对象。
要保存结果,您应该将其分配回words
,如下所示:
words = sentence.split(" ")
words = words.map do |word|
translate_word(word)
end
或者改为使用#map!
。