psharma psharma - 14 days ago 5x
Ruby Question

Capitalize each word except selected words in an array

Right now I have

value = "United states of america"
words_to_ignore = ["the","of"]
new_string = value.split(' ').map {|w| w.capitalize }.join(' ')

What I am trying to do here is except the word
, I want the rest capitalized. So the output would be
United States of America
. Now I am not sure, how exactly to do this.


Try this:

  new_string = value.split(' ')
    .each{|i| i.capitalize! if ! words_to_ignore.include? i }
    .join(' ')