#この記事について
最近始めた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