Finding the element of a Ruby array with the maximum value for a particular attribute

前端 未结 3 466
北海茫月
北海茫月 2020-12-04 23:01

There is probably a very simple answer to this question, but I can\'t for the life of me figure it out at the moment. If I have a ruby array of a certain type of objects, an

相关标签:
3条回答
  • 2020-12-04 23:43

    You can also sort the array and then get max, min, second largest value etc.

    array = array.sort_by {|k,v| v}.reverse
    
    puts hash[0]["key"]
    
    0 讨论(0)
  • 2020-12-04 23:44

    Does this help?

    my_array.max {|a,b| a.attr <=> b.attr }
    

    (I assume that your field has name attr)

    0 讨论(0)
  • 2020-12-04 23:48
    array.max_by do |element|
      element.field
    end
    

    Or:

    array.max_by(&:field)
    
    0 讨论(0)
提交回复
热议问题