我想迭代一个数组,根据一个标准修改它的元素,并希望在每个元素之后插入另一个元素,除了最后一个元素之后。这样做最符合 Ruby 习惯的方式是什么?
def transform(input)
words = input.split
words.collect {|w|
if w == "case1"
"add that"
else
"add these" + w
end
# plus insert "x" after every element, but not after the last
}
end
例子:
transform("Hello case1 world!") => ["add theseHello", "x", "add that", "x", "add theseworld!"]