Annie H.
Annie H.

Reputation: 267

How to use max_by

I want to find the longest number sequence in an array like this:

string = input.scan(/(\d+)/)
string.max_by(&:length)

However, in the output I get only the first value in the array.

The whole code is:

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

I tried to use other methods, just to test how they would work and it turned out that none of them work, even those that I've copied from working examples. What can be wrong?

Upvotes: 0

Views: 1024

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54263

Your problem is with String#scan, not with max_by:

"12 3456 789".scan(/(\d+)/)
# [["12"], ["3456"], ["789"]]

It returns an array of arrays, because you used a matching group in the scan. For every match, it returns an array with all the groups. There's only 1 group in each match, so all those arrays have exactly 1 element.

max_by correctly returns the first array, because it has at least as many elements as all the others. You didn't notice the error because both Arrays and Strings respond to :length.

You want:

"12 3456 789".scan(/\d+/)
# ["12", "3456", "789"]

With max_by:

"12 3456 789".scan(/\d+/).max_by(&:length)
# "3456"

Upvotes: 6

Related Questions