我想迭代一个数组,根据一个条件修改它的元素,并希望在每个元素之后插入另一个元素,除了在最后一个元素之后。什么是最常用的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!"]
答案 0 :(得分:0)
def transform input
input.split.map do |w|
[
if w == 'case1'
'add that'
else
'add these' + w
end,
'x'
]
end.flatten[0..-2]
end
这通常写成:
def transform input
input.split.map do |w|
[ w == 'case1' ? 'add that' : 'add these' + w, 'x' ]
end.flatten[0..-2]
end
答案 1 :(得分:0)
对所需的输出进行一些假设,然后进行编辑:
def transform(input)
input.split.inject([]) do |ar, w|
ar << (w == "case1" ? "add that" : "add these" + w) << "x"
end[0..-2]
end
p transform("Hello case1 world!")
#=> ["add theseHello", "x", "add that", "x", "add theseworld!"]