在一行中选择数组的第一个和最后一个元素

Eat*_*igo 5 ruby arrays

我的任务是从数组中选择最高和最低数字.我想我已经知道我想做什么了,但只是努力以正确的格式访问信息以满足通过标准.

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

数字可能看起来像"80 9 17 234 100",并且要通过,我需要输出"9 234".我在尝试puts array.first.last,但一直无法弄清楚.

spi*_*ann 13

有一种Array#minmax方法可以完全满足您的需求:

array = [80, 9, 17, 234, 100]
array.minmax
#=> [9, 234]
Run Code Online (Sandbox Code Playgroud)

在您的high_and_low方法的上下文中使用,该方法接受输入并将结果作为字符串返回:

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"
Run Code Online (Sandbox Code Playgroud)


Log*_*man 0

最简单的方法是只使用minand max

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

如果标准没有内置函数,那么您的解决方案非常好。