psharma psharma - 10 months ago 52
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.

Answer Source

Try this:

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