0

I have an array of array as below:

a = [
      ["a", "v", 1], ["b", "w", 2], ["c", "x", 1], ["d", "y", 1],
      ["e", "z", 2], ["f", "one" , 3 ], ["g", "two" , 3 ], ["g", "one" , 4 ],
      ["f", "one" , 1 ], ["h", "one" , 5 ], ["f", "one" , 4 ],
      # ...
    ]

Then , i expect the result as 5 different arrays

a1 = [ ["a", "v", 1],["c", "x", 1], ["d", "y", 1], ["f", "one" , 1 ] ]
a2 = [ ["b", "w", 2], ["e", "z", 2] ] 
a3 = [ ["f", "one", 3], ["g", "two", 3] ]
a4 = [ ["g", "one", 4], ["f", "one", 4] ]
a5 = [ ["h", "one" , 5 ] ]
# ...
an = []

By doing the below code, i was able to sort it.

b = a.sort{|c,d|c[2] <=> d[2]}

How can i generate such a list.

Please help.Thanks in advance.

2 Answers 2

4

You could use partition:

a = [["a", "v", 1], ["b", "w", 2], ["c", "x", 1], ["d", "y", 1], ["e", "z", 2]]

a1, a2 = a.partition { |e| e[2] == 1 }

a1 #=> [["a", "v", 1], ["c", "x", 1], ["d", "y", 1]]
a2 #=> [["b", "w", 2], ["e", "z", 2]]

With more than 2 values, you could use group_by:

a = [
  ["a", "v", 1], ["b", "w", 2], ["c", "x", 1], ["d", "y", 1],
  ["e", "z", 2], ["f", "one" , 3 ], ["g", "two" , 3 ], ["g", "one" , 4 ],
  ["f", "one" , 1 ], ["h", "one" , 5 ], ["f", "one" , 4 ]
]

hash = a.group_by { |e| e[2] }
#=> { 1=>[["a", "v", 1], ["c", "x", 1], ["d", "y", 1], ["f", "one", 1]], 
#     2=>[["b", "w", 2], ["e", "z", 2]],
#     3=>[["f", "one", 3], ["g", "two", 3]],
#     4=>[["g", "one", 4], ["f", "one", 4]],
#     5=>[["h", "one", 5]] }

To access the arrays, you can use hash[1], hash[2], etc. or you can assign them to variables:

a1, a2, a3, a4, a5 = hash.values_at(1, 2, 3, 4, 5)

a1 #=> [["a", "v", 1], ["c", "x", 1], ["d", "y", 1], ["f", "one", 1]]
a2 #=> [["b", "w", 2], ["e", "z", 2]]
a3 #=> [["f", "one", 3], ["g", "two", 3]]
a4 #=> [["g", "one", 4], ["f", "one", 4]]
a5 #=> [["h", "one", 5]]
Sign up to request clarification or add additional context in comments.

2 Comments

Fussy readers might be thinking, "given was an index into a, from which 1 was computed".
Perfect. Thank you @Stefan.
0

Select would be the more readable option:

a.select do |v| v.third == 1 end
 => [["a", "v", 1], ["c", "x", 1], ["d", "y", 1]]

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.