0

如果我有这样的数组:

[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

我想根据这个任意索引数组选择该数组的一个子集:

[0,1,4,7,8,13,14,15,18,19]

结果是第一个数组的这个子集:

[1,2,5,8,9,14,15,16,19,20]

我的问题是,如何从索引数组和起始数组中创建一个简单的函数(1 或 2 行)来获取子集?

4

3 回答 3

3
arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
indexes = [0,1,4,7,8,13,14,15,18,19]

arr.values_at(*indexes) # => [1, 2, 5, 8, 9, 14, 15, 16, 19, 20]
于 2013-04-26T04:46:00.903 回答
0
arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
index = [0,1,4,7,8,13,14,15,18,19]
arr.select.with_index{|m,i| m if index.include? i}
#=> [1, 2, 5, 8, 9, 14, 15, 16, 19, 20]
于 2013-04-26T07:32:40.090 回答
0
arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
index = [0,1,4,7,8,13,14,15,18,19]

arr.each_with_index {|value,index| p value if indexes.include?(index)}
于 2013-04-26T08:32:37.260 回答