How to find a min/max with Ruby

后端 未结 6 2204
长情又很酷
长情又很酷 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 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]
    

提交回复
热议问题