1

I'm new to Ruby and would like to know if there is a better way to solve the following problem.

I have an array that looks like this:

[6, 1, 3, 6, 2, 4, 1, 3, 2, 3]

I'd like to turn it into this:

[ [1,1], [2,2], [3,3,3], [4], [], [6,6] ]

This is my current solution (again, I'm new to Ruby):

def split_array_into_arrays(array)
  max_num = array.max
  arrays = Array.new(max_num) { Array.new }

  array.each do |num|
    arrays[num-1] << num
  end

  arrays
end

arrays = split_array_into_arrays([6, 1, 3, 6, 2, 4, 1, 3, 2, 3])
puts arrays.inspect

Produces:

[[1, 1], [2, 2], [3, 3, 3], [4], [], [6, 6]]

Note: I realize I am not handling possible errors.

How might an experienced Ruby developer implement this?

4
  • 1
    why would you need empty arrays where there is no number? e.g. 5 Commented Jun 9, 2015 at 19:55
  • 1
    Normally group_by would be sufficient, but it appears you want to have an explicit empty array for the missing 5? Commented Jun 9, 2015 at 19:56
  • 1
    Yup.. that's why I'm asking. In order to give a good answer you need details like this. Maybe array.sort.group_by{|x| x}.values is enough for you Commented Jun 9, 2015 at 19:57
  • Thanks guys. Yes, for this contrived example, I would like "missing" numbers to be represented by empty arrays. I'm simply using this stuff to better understand Ruby - this isn't code I'm going to use for anything serious. Commented Jun 9, 2015 at 20:09

1 Answer 1

2
ar = [6, 1, 3, 6, 2, 4, 1, 3, 2, 3]

(1..ar.max).map{|n| [n]*ar.count(n)}
# => [[1, 1], [2, 2], [3, 3, 3], [4], [], [6, 6]]
Sign up to request clarification or add additional context in comments.

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.