如何使用 Ruby 找到最小值/最大值 [英] How to find a min/max with Ruby

查看:56
本文介绍了如何使用 Ruby 找到最小值/最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 min(5,10)Math.max(4,7).Ruby 中是否有实现此效果的函数?

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

推荐答案

你可以做

[5, 10].min

[4, 7].max

它们来自 Enumerable 模块,所以任何包含 Enumerable 将使这些方法可用.

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

v2.4 引入了自己的 Array#minArray#max,它们比 Enumerable 的方法快得多,因为它们跳过了调用 #each.

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

@nicholasklick 提到了另一个选项,Enumerable#minmax,但这次返回一个 [min, max] 数组.

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

[4, 5, 7, 10].minmax
=> [4, 10]

这篇关于如何使用 Ruby 找到最小值/最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆