Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ruby – Group array into nested arrays, and each nested array to have a specific length

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]] 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading