Skip to content

Instantly share code, notes, and snippets.

@RickGriff
Created January 21, 2018 21:27
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/6537371cb3208b8602eb48f8a62fe013 to your computer and use it in GitHub Desktop.
Save RickGriff/6537371cb3208b8602eb48f8a62fe013 to your computer and use it in GitHub Desktop.
Codewars Challenge: Title Case
# A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.
# Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The list of minor words will be given as a string with each word separated by a space.
# Your function should ignore the case of the minor words string -- it should behave in the same way even if the case of the minor word string is changed.
# ###Arguments (Haskell)
# First argument: space-delimited list of minor words that must always be lowercase except for the first word in the string.
# Second argument: the original string to be converted.
# ###Arguments (Other languages)
# First argument (required): the original string to be converted.
# Second argument (optional): space-delimited list of minor words that must always be lowercase except for the first word in the string. The JavaScript/CoffeeScript tests will pass undefined when this argument is unused.
# ###Example
# title_case('a clash of KINGS', 'a an the of') # should return: 'A Clash of Kings'
# title_case('THE WIND IN THE WILLOWS', 'The In') # should return: 'The Wind in the Willows'
# title_case('the quick brown fox') # should return: 'The Quick Brown Fox'
#-----
#My Solution
def title_case(title, minor_words='')
return "" if title.empty?
words = title.split
minors = minor_words.split.map! { |minor_word| minor_word.downcase } #array of downcase minor words
words.each do |word|
if minors.include? word.downcase
word.downcase!
else
word.capitalize!
end
end
words[0].capitalize! #capitalize the first word
words.join(" ")
end
#Again, my solutions feels somewhat clunky. After reviewing Codewars solutions,
#I see I could use the ternary operator to make the conditional logic more concise.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment