Reputation: 197
This is my array : array = ["1", "Hel", "6", "3", "lo" ]
I want to output the smallest number in the array. Then I want to output the largest number in the array? How do I achieve this? Thanks!
Upvotes: 0
Views: 3543
Reputation: 581
we can use unicode [[:digit:]] instead writing regular expression as array.join(',').scan(/[[:digit:]]/).minmax_by(&:to_i)
Upvotes: 0
Reputation: 110675
Another way:
array.join(',').scan(/-?\d+/).minmax_by(&:to_i)
#=> ["-4", "6"]
Upvotes: 0
Reputation: 1020
Another variation to work with negative numbers
smalles, largest =
["1", "Hel", "6", "3", "lo","-9" ].select { |x| x[/^-?\d+$/] }.minmax_by(&:to_i)
smallest # => -9 largest # => 6
Upvotes: 1
Reputation: 101
Well it depends how you want to handle the string elements that aren't easily parsed into numbers. Like "Hel" and "lo".
If you do this:
array.map {|x| Integer(x) rescue nil }.compact.min
array.map {|x| Integer(x) rescue nil }.compact.max
Then you'll ignore those, which is probably the right thing, assuming you don't have some reason for considering "Hel" and "lo" to have numerical values.
Upvotes: 3
Reputation: 37409
numbers = array.select { |x| x[/^-?\d+$/] }.map(&:to_i)
# => [1, 6, 3]
numbers.min
# => 1
numbers.max
# => 6
Upvotes: 1
Reputation: 168091
smallest, largest =
["1", "Hel", "6", "3", "lo" ].reject{|s| s =~ /\D/}.minmax_by(&:to_i)
smallest # => "1"
largest # => "6"
Upvotes: 0