Skip to content

Instantly share code, notes, and snippets.

@RickGriff
Last active January 21, 2018 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RickGriff/6bee59c66ec6c4af10092d77a90645ae to your computer and use it in GitHub Desktop.
Save RickGriff/6bee59c66ec6c4af10092d77a90645ae to your computer and use it in GitHub Desktop.
Codewars Challenge: Format Names
# Given: an array containing hashes of names
# Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.
# Example:
# list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ])
# # returns 'Bart, Lisa & Maggie'
# list([ {name: 'Bart'}, {name: 'Lisa'} ])
# # returns 'Bart & Lisa'
# list([ {name: 'Bart'} ])
# # returns 'Bart'
# list([])
#-----
#My Solution:
def list names
count = 0
return names[0][:name] if names.size == 1
names.each_with_object("") do |name_hash, str|
if ( count == names.length - 1 )
str << " & #{name_hash[:name]}" #ampersand before the last word
elsif count == 0
str << "#{name_hash[:name]}" #no comma before the first word
else
str << ", #{name_hash[:name]}"
end
count +=1
end
end
#This felt clunky. I liked the top 'Best Practice' solution on Codewars - use map first to get an array,
#pop and edit the last name, rejoin the names, and append the last.
#Codewars Best Practice Solution:
def list names
names = names.map { |name| name[:name] }
last_name = names.pop
return last_name.to_s if names.empty?
"#{names.join(', ')} & #{last_name}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment