Jun Jun - 1 year ago 165
Ruby Question

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(", ")}"




Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download