2013-11-20 115 views
1

在紅寶石多個陣列我有以下的數組:拆分陣列成基於索引

array = [["Group EX (Instructor)", 0.018867924528301886], ["Personal Reasons", 0.018867924528301886]]

,我需要拆分此陣列起來,動態地,成兩個陣列:

text_array = ["Group EX (Instructor)", "Personal Reasons"] 

number_array = [0.018867924528301886,0.018867924528301886] 

我目前正在這樣做,這是不正確的:

array.each do |array| 
    text_array << array[0] 
    number_array << array[1] 
end 

回答

2

只需使用#transpose

array = [["Group EX (Instructor)", 0.018867924528301886], ["Personal Reasons", 0.018867924528301886]] 
a1, a2 = array.transpose 
#=> [["Group EX (Instructor)", "Personal Reasons"], 
[0.018867924528301886, 0.018867924528301886]] 

修復現有的代碼,

text_array = array.map { |x| x[0] } #give back first element of each subarray 
number_array = array.map { |x| x[1] } #give back second element of each subarray 
1

我會做如下:

array = [["Group EX (Instructor)", 0.018867924528301886], ["Personal Reasons", 0.018867924528301886]] 
text_array,number_array = array.flatten.partition{|e| e.is_a? String } 
text_array # => ["Group EX (Instructor)", "Personal Reasons"] 
number_array # => [0.018867924528301886, 0.018867924528301886] 
0

這同樣適用:

text_array, number_array = array.first.zip(array.last) 

transpose顯然是你想要什麼。