Ruby:如何找到最小数组元素的索引?
有什么办法可以重写得更优雅吗?我认为这是一段糟糕的代码,应该重构。
>> a = [2, 4, 10, 1, 13]
=> [2, 4, 10, 1, 13]
>> index_of_minimal_value_in_array = a.index(a.min)
=> 3
Is there any way to rewrite this more elegant? I think, that it's a bad piece of code and should be refactored.
>> a = [2, 4, 10, 1, 13]
=> [2, 4, 10, 1, 13]
>> index_of_minimal_value_in_array = a.index(a.min)
=> 3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我相信这只会遍历数组一次并且仍然很容易阅读:
I believe this will traverse the array only once and is still easy to read:
这只会遍历数组一次,而 ary.index(ary.min) 会遍历数组两次:
This traverses the array only once whereas
ary.index(ary.min)
would traverse it twice:我实际上喜欢 @andersonvom 的答案,它只需要循环数组一次,仍然可以获得索引。
如果您不想使用
ary.each_with_index.min
,您可以执行以下操作:I actually like @andersonvom 's answer, it only need to loop the array once and still get the index.
And in case you don't want to use
ary.each_with_index.min
, here is what you can do: