谁喜欢这则贴文,初探 case...when 用法,Ruby 30 天刷题修行篇第十六话

嗨,我是 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 常用的 ==。

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


<<:  【Day 18】- 像个使用者的爬虫 Selenium

>>:  D18 - 彭彭的课程# Python Package 封包的设计与使用

冒险村10 - or equals

10 - or equals Ruby 的 ||=(or equals)运算符号使用频率是个使用频率...

SQL Server Agent 权限 - 心得分享

DBABootcamp 没有 SA 权限的使用者,要如何管理 SQL Agent Jobs (作业)...

[Day8]Rare Easy Problem

上一篇介绍了2 the 9s,是一题会需要重复执行的题目,使用回圈跟副程序会比较容易执行,整体上不会...

【在厨房想30天的演算法】Day 16 演算法 : 排序 sort III 希尔、摇晃、基数

Aloha!又是我少女人妻 Uerica ~ 我每天看到时间快接近午夜 12 点,都能感受到灰姑娘的...

【DAY 5】主管签名好难追怎麽办? Power Automate - 核准

哈罗 ~ 大家好 ~ 欢迎回来 ~ 相信征战职场的大家,一定会有个苦恼的问题,那就是每次老板签公文都...