Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - remove underscores and capitalize

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)
like image 447
Jun Avatar asked Nov 17 '16 00:11

Jun


4 Answers

I came here looking for a way to modify a string with underscores to be more class-name-like. Rails has String#classify.

irb> 'some_class_string'.classify
=> "SomeClassString"
like image 155
taylorthurlow Avatar answered Nov 13 '22 22:11

taylorthurlow


In Rails you can use titleize

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

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

like image 38
Rahul Patel Avatar answered Nov 13 '22 20:11

Rahul Patel


You can use this one liner

str.split('_').map(&:capitalize).join(' ')

This takes a string str and splits it where the underscores are, then capitalizes each word then joins the words together with a space. Example

"fourth_of_july".split('_') -> ["fourth", "of", "july"]
["fourth", "of", "july"].map(&:capitalize) -> ["Fourth", "Of", "July"]
["Fourth", "Of", "July"].join(' ') -> "Fourth Of July"
like image 11
Eli Sadoff Avatar answered Nov 13 '22 21:11

Eli Sadoff


Using recursion we can go through your nested hash, find all your keys and apply the change:

def key_changer hash
  hash.map do |k,v|
    [ k.to_s.scan(/[a-zA-Z]+/).map(&:capitalize).join(' '),
      v.class == Hash ? key_changer(v) : v ]
  end.to_h
end

key_changer holiday_dec #=>

#{ "Winter" => { "Christmas"      => ["Lights", "Wreath"],
#                "New Years"      => ["Party Hats"] },
#  "Summer" => { "Fourth Of July" => ["Fireworks", "BBQ"] },
#  "Fall"   => { "Thanksgiving"   => ["Turkey"] },
#  "Spring" => { "Memorial Day"   => ["BBQ"]}
#}

It's not exactly what you asked for (only realised after answering) but I'll leave this answer up nonetheless as you may find it useful.

like image 1
Sagar Pandya Avatar answered Nov 13 '22 20:11

Sagar Pandya