如何基于Ruby中该数组的索引数组创建数组的子集

时间:2013-04-26 04:44:34

标签: ruby arrays indexing subset

如果我有这样的数组:

[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行)来获取子集?

3 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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]

答案 2 :(得分: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)}