iT邦幫忙

2021 iThome 鐵人賽

DAY 11
0
自我挑戰組

從真「新」鎮出發!30天的刷題修行篇,讓寫程式成為新必殺技系列 第 11

輕鬆排序!sort 的延伸用法,Ruby 30 天刷題修行篇第十一話

嗨,我是 A Fei,大家週末過得如何?五倍振興券想好怎麼花了嗎?如果沒有,可以給我(被揍),啊不是,也可以考慮捐給弱勢團體唷,這也是我最近才知道的,原來振興券不只可以消費,也可以捐助。

閒聊完後,馬上讓我們看看今天的題目:
(題目來源:Codewars


Write a function that takes an array of strings as an argument and returns a sorted array containing the same strings, ordered from shortest to longest.

For example, if this array were passed as an argument:

["Telescopes", "Glasses", "Eyes", "Monocles"]

Your function would return the following array:

["Eyes", "Glasses", "Monocles", "Telescopes"]

All of the strings in the array passed to your function will be different lengths, so you will not have to decide how to order multiple strings of the same length.


題目要我們把一陣列中的字串(元素),依照長度依序排好,我馬上想到 sort 方法,這邊可以介紹一下 sort 的進階用法,一般 sort 是昇序排列,那如果要降序呢?你可以在 sort 後面接上 block,寫法是 array.sort {|a, b| b <=> a },<=> 運算子將在 a 小於 b 時回傳負數,當 a 大於 b 時回傳正數,當 a 和 b 相等時回傳 0,藉此兩兩比較、排序陣列中的元素。讓我們直接試試:

a = ["a", "b", "c", "d", "e"]
a.sort {|a, b| b <=> a } 
  # => ["e", "d", "c", "b", "a"]

同樣的道理,反過來寫的話就是昇序,以下為我的解答:

def sort_by_length(arr)
  arr.sort {|a, b| a.length <=> b.length }
end

對比評分最高的答案:

def sort_by_length(arr)
  arr.sort_by(&:length)
end

它更加準確地用了 sort_by 方法,sort_by 後面可以接上要排序的條件,例如官網的例子:

%w{apple pear fig}.sort_by { |word| word.length }
  #=> ["fig", "pear", "apple"]

而 &: 在上一章提過,這算是一種縮寫法。

好啦,今天的解題紀錄就到這,大家掰掰~


上一篇
誰比誰長,迴圈和 reduce 用法,Ruby 30 天刷題修行篇第十話
下一篇
實用的 each_cons 方法,Ruby 30 天刷題修行篇第十二話
系列文
從真「新」鎮出發!30天的刷題修行篇,讓寫程式成為新必殺技16
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言