iT邦幫忙

2021 iThome 鐵人賽

DAY 14
0
自我挑戰組

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

誰喜歡這則貼文,初探 case...when 用法,Ruby 30 天刷題修行篇第十六話

  • 分享至 

  • twitterImage
  •  

嗨,我是 A Fei,讓我們看看今天的題目:
(題目來源:Codewars


You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.

Implement the function which takes an array containing the names of people that like an item. It must return the display text as shown in the examples:

[]                                -->  "no one likes this"
["Peter"]                         -->  "Peter likes this"
["Jacob", "Alex"]                 -->  "Jacob and Alex like this"
["Max", "John", "Mark"]           -->  "Max, John and Mark like this"
["Alex", "Jacob", "Mark", "Max"]  -->  "Alex, Jacob and 2 others like this"

以下是我的答案:

def likes(names)
  case names.size
  when 0
    "no one likes this"
  when 1
    "#{names[0]} likes this"
  when 2
    "#{names[0]} and #{names[1]} like this"
  when 3
    "#{names[0]}, #{names[1]} and #{names[2]} like this"
  else
    "#{names[0]}, #{names[1]} and #{names.size - 2} others like this"
  end  
end

當同一種狀況要判斷很多次時,可以用 case ... when,讓你的 code 更簡潔易懂。不過要注意的是,在 case ... when 裡面我們是用 === 去判斷是否相等,而不是 if ... else 常用的 ==。

由於和最高分解答一模一樣,這次就不解析了。


上一篇
歡迎進入 ip 的世界,Ruby 30 天刷題修行篇第十五話
系列文
從真「新」鎮出發!30天的刷題修行篇,讓寫程式成為新必殺技16
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言