rubycomparableenumerable

How, with Ruby, can I access and compare these nested array values?


I have this nested array:

[[1, 2, 3],                                                                   
 [1, 3, 6],                                                                   
 [1, 4, 12],                                                                  
 [1, 5, 5],                                                                   
 [1, 2, 3],                                                                   
 [1, 8, 7],                                                                   
 [2, 3, 3],                                      
 [2, 4, 9],                                      
 [2, 5, 2],                                      
 [2, 8, 4],                                      
 [3, 4, 6],                                      
 [3, 8, 1],                                      
 [5, 8, 2],                                      
 [2, 8, 4],                                      
 [7, 8, 9]]

and I am trying to find a succinct but readable way of:

  1. comparing and finding the maximum value from those values in index position[2] (i.e. 3rd element in each nested array) within each of the nested arrays.
  2. Returning the neighbouring values at index[0] and [1] from the same nested array containing the maximum value from point 1.

I've unsuccessfully played around with various methods such as #max, #max_by, #group_by, #with_index but I'm now at the stage where I could just do with some enlightenment from a more capable brain and programmer then me.


Solution

  • Finding the nested array with the max value on the last element:

    input = [[1, 2, 3], [1, 3, 6], [1, 4, 12], [1, 5, 5], [1, 2, 3], [1, 8, 7], [2, 3, 3], [2, 4, 9], [2, 5, 2], [2, 8, 4], [3, 4, 6], [3, 8, 1], [5, 8, 2], [2, 8, 4], [7, 8, 9]]
    input.max_by(&:last)
    #=> [1, 4, 12]
    

    And to only return its first two values:

    input.max_by(&:last).take(2)
    #=> [1, 4]