arraysrubystringintegermin

How do I find the minimum element in an array of strings, but only considering integers?


I'm using Ruby 2.4. I have an array of strings that are supposed to be integers ...

["1", "55", "25", ... ]

I have the following for figuring out the minimum number in the array

data.map(&:to_i).min

This works great, except for the times when a non-integer string creeps into my array, like

["1", "a", "2", "3"]

With my data.map(&:to_i).min line, the above returns zero. How do I modify my code so that it will only take the min of elements in the array that are actually integers?


Solution

  • You have a few ways of doing this, but the easiest is to screen out non-numerical values if you want to ignore the garbage:

    data = ["1", "a", "2", "3"]
    data.grep(/\A\-?\d+\z/).map(&:to_i).min
    # => 1
    

    The grep method makes it pretty easy to pick out things that match a particular pattern, as well as many other things.