0%

codewar-取最大值與最小值

題目說明:取最大值與最小值

1
Test.assert_equals(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"), "542 -214")

起始內容:

1
2
def high_and_low(numbers)
end

解題步驟:

1.把字串裡的每個字用split分開,並且得到新的陣列

1
2
3
4
5
def high_and_low(numbers)
numbers.split
end

=>["4", "5", "29", "54", "4", "0", "-214", "542", "-64", "1", "-3", "6", "-6"]

2.用map對陣列每個元素做轉換成數字

1
2
3
4
5
def high_and_low(numbers)
numbers.split.map{|x| x.to_i}
end

=>[4, 5, 29, 54, 4, 0, -214, 542, -64, 1, -3, 6, -6]

3.用minmax取最小及最大值,再reverse把最大值放前面

1
2
3
4
5
def high_and_low(numbers)
numbers.split.map{|x| x.to_i}.minmax.reverse
end

=>[542, -214]

4.最後join把陣列變回字串,並且在中間加上空格

1
2
3
4
5
def high_and_low(numbers)
numbers.split.map{|x| x.to_i}.minmax.reverse.join(' ')
end

=>"542 -214"