如何使用max_by

Ann*_* H. 0 ruby methods

我想找到数组中最长的数字序列,如下所示:

string = input.scan(/(\d+)/)
string.max_by(&:length)
Run Code Online (Sandbox Code Playgroud)

但是,在输出中我只得到数组中的第一个值.

整个代码是:

puts "Enter a string with letters and numbers"
input = gets
string = input.scan(/(\d+)/)
puts string.max_by(&:length)
Run Code Online (Sandbox Code Playgroud)

我尝试使用其他方法,只是为了测试它们如何工作,结果证明它们都不起作用,即使是那些我从工作示例中复制过的方法.有什么不对?

Eri*_*nil 6

你的问题是String#scan,而不是max_by:

"12 3456 789".scan(/(\d+)/)
# [["12"], ["3456"], ["789"]]
Run Code Online (Sandbox Code Playgroud)

它返回一个数组数组,因为您在扫描中使用了匹配组.对于每个匹配,它返回包含所有组的数组.每个匹配中只有1个组,因此所有这些数组都只有1个元素.

max_by正确返回第一个数组,因为它至少具有与其他数组一样多的元素.您没有注意到错误,因为数组和字符串都会响应:length.

你要:

"12 3456 789".scan(/\d+/)
# ["12", "3456", "789"]
Run Code Online (Sandbox Code Playgroud)

max_by:

"12 3456 789".scan(/\d+/).max_by(&:length)
# "3456"
Run Code Online (Sandbox Code Playgroud)