# Max\_by and other methods simply not working

**URL:** <https://www.ruby-forum.com/t/max-by-and-other-methods-simply-not-working/245337>\
**Category:** Ruby-Forum\
**Created:** [April 22, 2017, 4:22am UTC](https://www.ruby-forum.com/t/max-by-and-other-methods-simply-not-working/245337 "2017-04-22T04:22:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Rafa\_F](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/958977/32.png) [@Rafa\_F](https://www.ruby-forum.com/u/Rafa_F)\
**Post date:** [April 22, 2017, 4:22am UTC](https://www.ruby-forum.com/t/max-by-and-other-methods-simply-not-working/245337/1 "2017-04-22T04:22:37Z")

</div>

Hello to everyone!

I am quite new to ruby and I’m simply wanted 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.  
I tried to use other methods, just to test how they would work and  
turned out that none of them work, even those that I’ve copied from  
working examples. What can be wrong?  
The whole code is:

puts “Enter a string with letters and numbers”  
input = gets  
string = input.scan(/(\d+)/)  
puts string.max\_by(&:length)

Thanks for any help!

---

<div class="post-metadata">

**Author:** ![SouravGoswami](https://www.ruby-forum.com/user_avatar/www.ruby-forum.com/souravgoswami/32/2543_2.png) [@SouravGoswami](https://www.ruby-forum.com/u/SouravGoswami)\
**Post date:** [May 5, 2019, 7:52pm UTC](https://www.ruby-forum.com/t/max-by-and-other-methods-simply-not-working/245337/2 "2019-05-05T19:52:56Z")

</div>

# So basically you would do instead is

`some_string.scan(/(\d+)/).flatten.max_by(&:length)`  
_or_  
`some_string.scan(/(\d+)/).join(' ').split.max_by(&:length)`  
_or_  
`some_string.scan(/(\d+)/).map(&:first).max_by(&:length)`

# Explanation

When you use scan(/(\d+)/) method on a String object, it will just scan for digits, and group them in an array. For example:

```
'4433234 123 1234 43322 444444'.scan(/(\d+)/)
# => [["4433234"], ["123"], ["1234"], ["43322"], ["444444"]]

```

So each array in the above return value has size / length / count 1:  
‘4433234 123 1234 43322 444444’.scan(/(\d+)/).map &:length  
# =\> [1, 1, 1, 1, 1]

So max\_by will not work as intended.
