2013-04-26 43 views
0

如果我有一個這樣的數組:如何創建基於索引的使用Ruby數組的數組的數組的一個子集

[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
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] 
+0

不錯,我知道有一些簡單 – Eric 2013-04-26 04:47:51

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] 
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)} 
相關問題