gpt4 book ai didi

Ruby:如何找到最小数组元素的索引?

转载 作者:数据小太阳 更新时间:2023-10-29 06:32:35 26 4
gpt4 key购买 nike

有什么办法可以更优雅地重写这个吗?我认为,这是一段糟糕的代码,应该重构。

>> a = [2, 4, 10, 1, 13]
=> [2, 4, 10, 1, 13]
>> index_of_minimal_value_in_array = a.index(a.min)
=> 3

最佳答案

我相信这只会遍历数组一次并且仍然很容易阅读:

numbers = [20, 30, 40, 50, 10]           # => [20, 30, 40, 50, 10]
elem, idx = numbers.each_with_index.min # => [10, 4]

关于Ruby:如何找到最小数组元素的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4964256/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com