Ruby 是否有一个函数可以在包含整数和字符串的数组中查找最大值索引?
在这里的示例中,是否有一种方法可以正确打印max int(7654)索引(5)? 我还没有找到一种方法来处理一个包含int和字符串的数组,只有那些包含严格int的数组Ruby 是否有一个函数可以在包含整数和字符串的数组中查找最大值索引?,ruby,Ruby,在这里的示例中,是否有一种方法可以正确打印max int(7654)索引(5)? 我还没有找到一种方法来处理一个包含int和字符串的数组,只有那些包含严格int的数组 array = ["me", 2345, "you", 345, "him", 7654, "her", 25] arraybutonlynumbers = [2345, 345, 7654, 25] puts array.each_with_ind
array = ["me", 2345, "you", 345, "him", 7654, "her", 25]
arraybutonlynumbers = [2345, 345, 7654, 25]
puts array.each_with_index.max[1] #comparison of Array with Array failed (ArgumentError)
puts arraybutonlynumbers.each_with_index.max[1] #no error
但是请注意,to_i
将不以数字开头的字符串转换为0
,如果数组中没有正整数,则可能会产生不需要的结果。使用Select、Max和Index
使用内置数组方法,您可以在三个概念性步骤中找到所需的中间结果:
# find largest integer in a mixed array
array.select { |e| e.is_a? Integer }.max
#=> 7654
# find index of last return value
array.index _
#=> 5
但是,为了获得所需的输出,您需要将其重构为保留中间结果的内容,以便能够以预期的格式返回它们。例如:
def max_integer_with_index array
max_int = array.select { |e| e.is_a? Integer }.max
max_int_idx = array.index max_int
[max_int, max_int_idx]
end
max_integer_with_index [
"me", 2345, "you", 345, "him", 7654, "her", 25
]
#=> [7654, 5]
array.index array.select { |e| e.is_a? Integer }.max
#=> 5
如果不需要中间值,还可以将查找索引的过程简化为一行代码。例如:
def max_integer_with_index array
max_int = array.select { |e| e.is_a? Integer }.max
max_int_idx = array.index max_int
[max_int, max_int_idx]
end
max_integer_with_index [
"me", 2345, "you", 345, "him", 7654, "her", 25
]
#=> [7654, 5]
array.index array.select { |e| e.is_a? Integer }.max
#=> 5
警告
请注意,如果除了忽略数组中的字符串对象之外,还想做其他事情,则可能需要实现(继承自Enumerable;另请参见)在整数和字符串之间绘制自己的自定义比较。我也是这么想的,但还没有找到处理
数组=[“我”、-2345、“你”、-345]
。我想人们可以编写数组。每个数组都有{el,{el,{u124; el.的{u index.max_。}是一个字符串吗?-Float::INFINITY:el}
,但这有点难看。你确定最大值的逻辑是什么?例如,是什么使7654
比的“你”大
在你的例子中?@seasonalz:你为什么不简单地在数组中循环(使用每个带有索引的\u
)并手动计算最大值,只要一个元素恰好是一个数字?