1

I have the following array:

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 Answers 3

2

Simply use #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
Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

0

This too works:

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

but transpose clearly is what you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.