Ruby - remove underscores and capitalize

Jun picture Jun · Nov 17, 2016 · Viewed 9.1k times · Source

Okay so I'm trying to remove the underscores, as seen in some of the holidays (for example,fourth_of_july). Then I want to capitalize each of the words.

Expected result: fourth_of_july > Fourth Of July

so this is my code:

holiday_dec = {

:winter => {
   :christmas => ["Lights", "Wreath"],
   :new_years => ["Party Hats"]
 },
 :summer => {
   :fourth_of_july => ["Fireworks", "BBQ"]
 },
 :fall => {
   :thanksgiving => ["Turkey"]
 },
 :spring => {
   :memorial_day => ["BBQ"]
 }

}

def all_supplies_in_holidays(holiday_hash)

  holiday_hash.each do |seasons, holidays|

    holidays.each do |holidays, supplies|
      puts "#{seasons.to_s.capitalize}:"
      puts "  #{holidays.to_s.tr("_"," ").capitalize}: #{supplies.join(", ")}"
    end

  end

end

all_supplies_in_holidays(holiday_dec)

Answer

Rahul Patel picture Rahul Patel · May 24, 2017

In Rails you can use titleize

'fourth_of_july'.titleize => "Fourth Of July"

https://apidock.com/rails/Inflector/titleize