Ruby 迭代数组,修改和插入其他元素
我想迭代一个数组,根据一个条件修改它的元素,并想在每个元素后面插入另一个元素,最后一个元素后面除外。最常用的Ruby方式是什么Ruby 迭代数组,修改和插入其他元素,ruby,Ruby,我想迭代一个数组,根据一个条件修改它的元素,并想在每个元素后面插入另一个元素,最后一个元素后面除外。最常用的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
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!"]
这通常写为:
def transform input
input.split.map do |w|
[ w == 'case1' ? 'add that' : 'add these' + w, 'x' ]
end.flatten[0..-2]
end
对期望的输出做出一些假设,并编辑:
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!"]
def变换(输入)
input.split.injection([])do | ar,w|
我可能会创建一个新的集合。一如既往,需要样本输入和样本输出。英语中很容易模棱两可。例如,每个元素后面是否都有一个“x”?真正地因为你的意思可能是“只在添加的每个新元素之后”。原始元素保留了吗?@DigitalRoss你完全正确,我的错!谢谢你指出目前为止看起来不错,但我希望结果是数组而不是字符串:[“添加”,“这些”,“这些”…]然后@DigitalRoss的答案更适合你。编辑以满足所需的输出。@Mel Nicholson:它没有失败:[[0..-2]#=>[]
优先于映射{…}。展平
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!"]