0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CodeWarでの勉強(ruby)④ case~when

Posted at

#この記事について
最近始めたCodewarを通じて学べたことを少しずつアウトプット

##問題

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 a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:

引数で配列を受け取るlikesメソッドを実装して、配列に含まれる情報から誰がイイねをしたか表示させるようにさせる。

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

##僕の回答

def likes(names)
  return "no one likes this" if names.empty?
  
  if names.count == 1
    "#{names[0]} likes this"
  elsif names.count == 2
    names.each { |n| }.join(" and ") << " like this"
  elsif names.count == 3
    "#{names[0]}, #{names[1]} and #{names[2]} like this"
  else
   others_count = names.count -2
    "#{names[0]}, #{names[1]} and #{others_count} others like this"   
  end
end

配列の長さによって返す情報を変えていくシンプルのやり方だと思う。
強調しておきたいのが、 return "no one likes this" if names.empty?というように人生で初めて1行完結のif文を書けたことだ!!!!!

##ベストプラクティス

めっちゃ見やすい。。。
複数の条件でやる場合はcase~whenの方が読みやすくてイイね。

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?