Selecting the first and last elements of an array in one row

My task is to select the highest and lowest numbers from the array. I think I have a good idea of ​​what I want to do, but I'm just trying to access the information in the correct format to meet the criteria for passing.

def high_and_low(numbers)
  array = numbers.split(" ").map! {|x| x.to_i}
  array.sort! {|a,b| b <=> a}
  puts array[0, -1]
end

The numbers may look like "80 9 17 234 100", and for the transfer I need to print "9 234". I tried puts array.first.last, but could not figure it out.

+4
source share
3 answers

There is a method Array#minmaxthat does exactly what you need:

array = [80, 9, 17, 234, 100]
array.minmax
#=> [9, 234]

Using in the context of your method high_and_low, which takes 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"
+12

- min max:

numbers = "80 9 17 234 100"
array = numbers.split(' ').map(&:to_i)
[array.min, array.max] #=> [9, 234]

, , .

0

, :

array.minmax.join("")

0

Source: https://habr.com/ru/post/1614150/


All Articles