user3222947
user3222947

Reputation: 197

Simple ruby array smallest integer?

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

Answers (6)

Bimal Prasad Pandey
Bimal Prasad Pandey

Reputation: 581

we can use unicode [[:digit:]] instead writing regular expression as array.join(',').scan(/[[:digit:]]/).minmax_by(&:to_i)

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110675

Another way:

array.join(',').scan(/-?\d+/).minmax_by(&:to_i)
  #=> ["-4", "6"]

Upvotes: 0

user944938
user944938

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

eboswort
eboswort

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

Uri Agassi
Uri Agassi

Reputation: 37409

numbers = array.select { |x| x[/^-?\d+$/] }.map(&:to_i)
# => [1, 6, 3] 
numbers.min
# => 1
numbers.max
# => 6

Upvotes: 1

sawa
sawa

Reputation: 168091

smallest, largest =
["1", "Hel", "6", "3", "lo" ].reject{|s| s =~ /\D/}.minmax_by(&:to_i)

smallest # => "1"
largest  # => "6"

Upvotes: 0

Related Questions