How to find a min/max with Ruby

后端 未结 6 2201
长情又很酷
长情又很酷 2020-12-04 05:29

I want to use min(5,10), or Math.max(4,7). Are there functions to this effect in Ruby?

相关标签:
6条回答
  • 2020-12-04 05:55

    If you need to find the max/min of a hash, you can use #max_by or #min_by

    people = {'joe' => 21, 'bill' => 35, 'sally' => 24}
    
    people.min_by { |name, age| age } #=> ["joe", 21]
    people.max_by { |name, age| age } #=> ["bill", 35]
    
    0 讨论(0)
  • 2020-12-04 06:01

    You can do

    [5, 10].min
    

    or

    [4, 7].max
    

    They come from the Enumerable module, so anything that includes Enumerable will have those methods available.

    v2.4 introduces own Array#min and Array#max, which are way faster than Enumerable's methods because they skip calling #each.

    @nicholasklick mentions another option, Enumerable#minmax, but this time returning an array of [min, max].

    [4, 5, 7, 10].minmax
    => [4, 10]
    
    0 讨论(0)
  • 2020-12-04 06:02

    All those results generate garbage in a zealous attempt to handle more than two arguments. I'd be curious to see how they perform compared to good 'ol:

    def max (a,b)
      a>b ? a : b
    end
    

    which is, by-the-way, my official answer to your question.

    0 讨论(0)
  • 2020-12-04 06:11

    You can use

    [5,10].min 
    

    or

    [4,7].max
    

    It's a method for Arrays.

    0 讨论(0)
  • 2020-12-04 06:15
    def find_largest_num(nums)
      nums.sort[-1]
    end
    
    0 讨论(0)
  • 2020-12-04 06:19

    In addition to the provided answers, if you want to convert Enumerable#max into a max method that can call a variable number or arguments, like in some other programming languages, you could write:

    def max(*values)
     values.max
    end
    

    Output:

    max(7, 1234, 9, -78, 156)
    => 1234
    

    This abuses the properties of the splat operator to create an array object containing all the arguments provided, or an empty array object if no arguments were provided. In the latter case, the method will return nil, since calling Enumerable#max on an empty array object returns nil.

    If you want to define this method on the Math module, this should do the trick:

    module Math
     def self.max(*values)
      values.max
     end
    end
    

    Note that Enumerable.max is, at least, two times slower compared to the ternary operator (?:). See Dave Morse's answer for a simpler and faster method.

    0 讨论(0)
提交回复
热议问题