Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting first and last elements of an array in one line

Tags:

arrays

ruby

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.

like image 545
Eats Indigo Avatar asked Nov 02 '15 13:11

Eats Indigo


1 Answers

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"
like image 76
spickermann Avatar answered Sep 24 '22 19:09

spickermann