My task is to select the highest and lowest numbers from an array. I think I've got a good idea what I want to do, but just struggling to access the information in the right format to meet the pass criteria.
def high_and_low(numbers)
array = numbers.split(" ").map! {|x| x.to_i}
array.sort! {|a,b| b <=> a}
puts array[0, -1]
end
Numbers might have looked like "80 9 17 234 100"
, and to pass, I need to output "9 234"
. I was trying puts array.first.last
, but have not been able to figure it out.
There is the Array#minmax
method that does exactly what you need:
array = [80, 9, 17, 234, 100]
array.minmax
#=> [9, 234]
Usage in the context of your high_and_low
method that takes the input and returns the result as strings:
def high_and_low(numbers)
numbers.split. # `split` splits at whitespaces per default
map(&:to_i). # does the same as `map { |x| x.to_i }`
minmax. # extracts min and max
reverse. # reverses order to maxmin
join(' ') # joins min and max with a whitespace
end
high_and_low('80 9 17 234 100')
#=> "234 9"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With