喜欢这个
oldArray = [[a, b, c, d],[e, f, g, h]]
我需要一行代码,它会在oldArray的每个元素中返回一个新的数组,比如元素2
newArray = coolLine(oldArray, 2)
newArray -> [c, g]
答案 0 :(得分:3)
这是元素编号2:
oldArray.map { |a| a[2] }
答案 1 :(得分:0)
答案 2 :(得分:0)
oldArray的每个元素中的第二个元素
oldArray = [[a, b, c, d],[e, f, g, h]]
newArray = coolLine(oldArray, 2)
newArray -> [c, g]
你想要的东西可以通过多种方式实现。最常见的是map
和zip
。
map
函数允许您处理序列并将其任何项重新计算为新值:
arr = [ [ 1,2,3 ], %w{ a b c }, [ 10,20,30] ]
# proc will be called twice
# 'item' will first be [ 1,2,3 ] then %w{ a b c } and so on
result = arr.map{|item|
item[1]
}
result -> 2, then 'b', then 20
因此,创建“coolLine”似乎非常简单。
但是,根据其他因素,zip可能会变得更好。 Zip接受N个序列并按顺序枚举它们,同时从所有序列中返回第N个元素。为什么,这几乎就是你所要求的:
arr = [ [ 1,2,3 ], %w{ a b c }, [ 10,20,30] ]
zipped = arr[0].zip(*arr[1..-1)
zipped -> [ [1,'a',10], [2,'b',20], [3,'c',30] ]
或者,你不喜欢[0] / * [1 ..- 1]技巧,你可以轻松编写自己的'清洁拉链',就像在这里https://stackoverflow.com/a/1601250/717732