基于索引将数组拆分为Ruby中的多个数组

时间:2022-10-23 12:18:32

I have the following array:

我有以下数组:

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

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

and I need to split this array up, dynamically, into two arrays:

我需要动态地将这个数组分成两个数组:

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

number_array = [0.018867924528301886,0.018867924528301886]

I'm currently doing this, which can't be the right way:

我目前正在这样做,这不是正确的方法:

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

3 个解决方案

#1


2  

Simply use #transpose.

只需使用#transpose。

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

Repairing your existing code,

修复现有代码,

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

#2


1  

I would do as below :

我会这样做:

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]

#3


0  

This too works:

这也有效:

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

but transpose clearly is what you want.

但转移清楚就是你想要的。

#1


2  

Simply use #transpose.

只需使用#transpose。

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

Repairing your existing code,

修复现有代码,

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

#2


1  

I would do as below :

我会这样做:

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]

#3


0  

This too works:

这也有效:

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

but transpose clearly is what you want.

但转移清楚就是你想要的。