Little by little output of what I learned through the recently started 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:
Implement the likes method that receives an array as an argument so that it can display who liked it from the information contained in the array.
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
I think it's a simple way to change the information returned depending on the length of the array.
I would like to emphasize that I was able to write a one-line complete if statement for the first time in my life, such as return" no one likes this "if names.empty?
! !! !! !! !!
Very easy to see. .. ..
If you do it under multiple conditions, case ~ when
is easier to read and is better.
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
Recommended Posts