More concise version of max/min without the block

前端 未结 3 1264
温柔的废话
温柔的废话 2021-01-06 07:09

I normally do [\'abc\', \'defg\'].max{|a, b| a.length <=> b.length}, but this seems like a lot of extra typing to compare the results of the same method o

相关标签:
3条回答
  • 2021-01-06 07:21

    For an array of Hashes:

    roomies = [{:name => "Habib", :age => 24}, {:name => "Tyler", :age => 25}]
    
    roomies.max_by{|a| a[:age]}[:age]
    
    => 25
    
    0 讨论(0)
  • 2021-01-06 07:25

    This is more concise:

    ['abc', 'defg'].max_by{|x| x.length }
    
    0 讨论(0)
  • 2021-01-06 07:40
    ['abcd', 'def'].max_by &:length
    
    0 讨论(0)
提交回复
热议问题