psharma
psharma

Reputation: 1289

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 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.

Upvotes: 4

Views: 1586

Answers (5)

Seralto
Seralto

Reputation: 1076

You can use this way to force always the same result:

downcase_words = ["of", "the"]
your_string.split(' ').each{ |word| (downcase_words.include? word.downcase) ? 
                                     word.downcase! : word.capitalize! }.join(' ')

And your_string could be:

'united states of america'
'UNITED STATES OF AMERICA'
'uNitEd stAteS oF aMerIca'

And the result will always be: "United States of America"

Upvotes: 0

Zach Kemp
Zach Kemp

Reputation: 11904

I propose using a hash to store the capitalization procedure and exceptions in one package:

value       = 'united states of america'
title_cases = Hash.new {|_,k| k.capitalize }.merge({'of' => 'of', 'off' => 'off'})
new_string  = value.split(" ").map {|w| title_cases[w] }.join(' ') #=> "United States of America"

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70939

Maybe try something like:

value = "United state of america"
words_to_ignore = ["the","of"]
new_string = value.split(' ').map do |w| 
  unless words_to_ignore.include? w
    w.capitalize
  else
    w
  end
end
new_string[0].capitalize!
new_string = new_string.join(' ')

Upvotes: 1

sawa
sawa

Reputation: 168101

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}

Upvotes: 1

Rahul Tapali
Rahul Tapali

Reputation: 10137

Try this:

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

Upvotes: 6

Related Questions