Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalize each word except selected words in an array

Tags:

arrays

ruby

nlp

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 of, I want the rest capitalized. So the output would be United States of America. Now I am not sure, how exactly to do this.

like image 606
psharma Avatar asked Jan 14 '23 06:01

psharma


2 Answers

Try this:

  new_string = value.split(' ')
    .each{|i| i.capitalize! if ! words_to_ignore.include? i }
    .join(' ')
like image 168
Rahul Tapali Avatar answered Jan 18 '23 23:01

Rahul Tapali


value = "United state of america"
words_to_ignore = Hash[%w[the of].map{|w| [w, w]}]
new_string = value.gsub(/\w+/){|w| words_to_ignore[w] || w.capitalize}
like image 27
sawa Avatar answered Jan 18 '23 22:01

sawa