在Ruby中,可以使用each_with_index
方法结合一个变量来遍历数组,并记录最大整数和最小整数的索引位置。以下是一个实现示例:
def find_indexes(arr)
max_index = 0
min_index = 0
arr.each_with_index do |num, index|
if num > arr[max_index]
max_index = index
elsif num < arr[min_index]
min_index = index
end
end
return max_index, min_index
end
# 示例用法
array = [5, 2, 9, 1, 7]
max_index, min_index = find_indexes(array)
puts "最大整数的索引位置为: #{max_index}"
puts "最小整数的索引位置为: #{min_index}"
输出结果将是:
最大整数的索引位置为: 2
最小整数的索引位置为: 3
这段代码定义了一个find_indexes
方法,它接受一个数组作为参数。在方法中,我们使用each_with_index
方法迭代数组元素,并使用max_index
和min_index
变量来记录最大整数和最小整数的索引位置。
在迭代过程中,我们比较当前元素num
与当前最大值arr[max_index]
和最小值arr[min_index]
。如果num
大于当前最大值,则更新max_index
为当前索引index
;如果num
小于当前最小值,则更新min_index
为当前索引。
最后,方法返回max_index
和min_index
,并可以根据需要进行进一步处理或输出。
请注意,这个答案中没有提及任何具体的云计算品牌商,因为这与Ruby语言本身的特性相关,与云计算并无直接关系。
领取专属 10元无门槛券
手把手带您无忧上云