我有以下数组:
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
答案 0 :(得分: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 :(得分: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]
答案 2 :(得分:0)
这也有效:
text_array, number_array = array.first.zip(array.last)
但transpose
显然是你想要的。