所以我写了这段代码:
def translate_word word
vowel = ["a", "e", "i", "o", "u"]
if vowel.include? word[0]
word = word + "ay"
elsif vowel.include? word[1]
word = word[1..-1] + word[0] + "ay"
else
word = word[2..-1] + word[0..1] + "ay"
end
end
将一个单词翻译成猪拉丁语。为了我的目的,效果很好。但是,如果我们想要翻译多个单词呢?
def translate string
vowel = ["a", "e", "i", "o", "u"]
words = string.split(" ")
words.each do |word|
if vowel.include? word[0]
word = word + "ay"
elsif vowel.include? word[1]
word = word[1..-1] + word[0] + "ay"
else
word = word[2..-1] + word[0..1] + "ay"
end
end
words.join(" ")
end
除非,如果我们尝试用一个单词做这个,它会注意到没有任何空格,比如说螺丝,然后返回一个字符串。当我尝试使用它时,甚至不会给我一个错误,但是.each不会做任何事情。
puts "apple".split
#=>apple
puts translate "apple"
#=>apple
这不是一个不可逾越的问题。我可以运行string.includes? “”然后运行两个略有不同的程序,具体取决于它是否存在。但这似乎非常不善言辞。什么是更好或更惯用的方式来处理字符串和循环?
答案 0 :(得分:3)
为block参数指定另一个值不会更改数组元素:
words.each do |word|
word = word + "ay" # <- this doesn't work as expected
end
要更改元素,您必须调用更改接收器的方法,例如:
words.each do |word|
word << "ay"
end
但是,您不必重复算法,只需为每个单词调用translate_word
:
def translate(string)
string.split.map { |word| translate_word(word) }.join(" ")
end
translate("apple orange")
#=> "appleay orangeay"
我在这里使用了split
和join
,但您也可以使用gsub
:
def translate(string)
string.gsub(/\w+/) { |word| translate_word(word) }
end
答案 1 :(得分:1)
据我所知,你没有操纵原来的数组字。
你需要这样的东西:
def translate string
vowel = ["a", "e", "i", "o", "u"]
words = string.split(" ")
words.each_with_index do |word, index|
if vowel.include? word[0]
word = word + "ay"
elsif vowel.include? word[1]
word = word[1..-1] + word[0] + "ay"
else
word = word[2..-1] + word[0..1] + "ay"
end
words[index] = word
end
words.join(" ")
end