有没有更优雅的方式来重写这段代码?我认为这是一段糟糕的代码,应该进行重构。
>> a = [2, 4, 10, 1, 13]
=> [2, 4, 10, 1, 13]
>> index_of_minimal_value_in_array = a.index(a.min)
=> 3
有没有更优雅的方式来重写这段代码?我认为这是一段糟糕的代码,应该进行重构。
>> 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]
Array#last
使它看起来很丑 (ary.each_with_index.min.last
)。 - kyryloary.each_with_index.min.second
更加优美。 - Obromios这种方法只遍历一次数组,而使用 ary.index(ary.min)
则需要遍历两次:
ary.each_with_index.inject(0){ |minidx, (v,i)| v < a[minidx] ? i : minidx }
ary.each_with_index.inject([Float::INFINITY,0]) { |(mv,mi), (v,i)| v<mv ? [v,i] : [mv,mi] }
- igrek阅读其他情况(查找所有且仅最小元素)可能会很有趣。
ary = [1, 2, 1]
# find all matching elements' indexes
ary.each.with_index.find_all{ |a,i| a == ary.min }.map{ |a,b| b } # => [0, 2]
ary.each.with_index.map{ |a, i| (a == ary.min) ? i : nil }.compact # => [0, 2]
# find last matching element's index
ary.rindex(ary.min) # => 2
each.with_index
将数组添加索引,生成一个包含原始元素和索引的数组数组,然后可以将其传递给其他转换器,如map
。each_with_index
想要迭代数组数组。这是一个微妙的区别,但我不想要一个each
循环,我想要进行转换。 - the Tin Man我其实很喜欢@andersonvom的回答,它只需要循环一次数组,就可以得到索引。
如果你不想使用ary.each_with_index.min
,那么你可以这样做:
ary = [2,3,4,5,1] # => [2,3,4,5,1]
_, index_of_minimal_value_in_array = ary.each_with_index.min # => [1, 4]
index_of_minimal_value_in_array # => 4