0

Create a method that takes two parameters. First parameter is an array of any length. Second parameter is N which will be the length of each nested array. For example:

# First parameter
water_depths = [32, 45, 12, 59, 14, 30, 11, 1, 20, 17, 18, 18, 40, 100, 399, 987, 210]

# Second parameter - N is the desired length of each nested array
3

def organize_depths(arr, n)
 # code goes here.
end

# Final result 
[[32, 45, 12], [59, 14, 30], [11, 1, 20], [17, 18, 18], [40, 100, 399], [987, 210]]

# Note - Last nested array's length does not have to be N length, but must not be longer than N.

1 Answers1

2

You can use the ruby each_slice method for this like below:

water_depths.each_slice(3).to_a
# [[32, 45, 12], [59, 14, 30], [11, 1, 20], [17, 18, 18], [40, 100, 399], [987, 210]] 
Sachin Singh
  • 993
  • 8
  • 16