Leia_Organa Leia_Organa - 1 year ago 78
Ruby Question

How to sort alphabetically within a multidimensional array?

I'm an intermediate Ruby developer. I'm working on some puzzles to brush up on Ruby and I'm trying to figure out how to go about sorting a multidimensional array.
Here's my code:

myArray = [['Jones', 'Layla'], ['Smith', 'Gary'], ['Williams', 'Nick'] ['Brown', 'Kyle']]

So I need to iterate through the array and through the sub-arrays, identify the last names, and alphabetize them. For some reason nothing I've been trying for the last two hours seems to be working. I've been searching high and low online. Can anyone help out? I've been trying variations of the following, below. Any pointers?

myArray.each { |sub_array|
sub_array.sort_by! { |x|
x[0].downcase #the x[0] element being the last name, which is the first element in each of the sub-arrays
return sub_array

edit: forgot to clarify, the end result should look like this:

myArray = [['Brown', 'Kyle']['Jones', 'Layla'], ['Smith', 'Gary'], ['Williams', 'Nick']]

Answer Source

If you want sort the array by the lastname (the first element of each sub array) you could do easily with this:

myArray.sort { |x,y| x[0] <=> y[0] }

myArray = [['Jones', 'Layla'], ['Smith', 'Gary'], ['Williams', 'Nick'], ['Brown', 'Kyle']]
 => [["Jones", "Layla"], ["Smith", "Gary"], ["Williams", "Nick"], ["Brown", "Kyle"]] 
myArray.sort { |x,y| x[0] <=> y[0] }
 => [["Brown", "Kyle"], ["Jones", "Layla"], ["Smith", "Gary"], ["Williams", "Nick"]]  

sort documentation here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download