mercredi 30 août 2017

Ruby Program not performing as expected? If block executes despite failing the condition

The Following program is intended to iterate over the holiday_hash, capitalise all keys and values and puts them out:

def all_supplies_in_holidays(holiday_hash)
  holiday_hash.each do |key, value|
  key_string = key.to_s
  key_string.capitalize!
  puts "#{key_string}:"
  value.each do |key2, value2|
    if key2 == :new_year || :fourth_of_july || :memorial_day 
     key_to_string = key2.to_s
     key_string1 = key_to_string.split
     final_array = []
     key_string1.each do |splitted_string|
     final_array = splitted_string.capitalize!
    end
    final_string = final_array.join(" ")
    print "#{final_string1}:"
  else
    key_string1 = key2.to_s
    print "#{key_string1}"
  end
  value2.each do |array_value|
    new_array_capitalized = []
    new_array_capitalized << array_value.capitalize!
    new_array.join(" ")
   end
  end
 end
end

The expected output format is:

Winter:
Christmas: Lights, Wreath
New Years: Party Hats
Summer:
Fourth of July: Fireworks, BBQ
Fall:
Thanksgiving: Turkey
Spring:
Memorial Day: BBQ

The holiday_hash is as follows:

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

The problem is:

  1. The if block executes even if the conditions fails to evaluate to true.

Suggestions needed:

  1. How can I simplify the process of capitalising symbols who have two words in them like :new_york to be capitalised to New York? (As the #capitalised method will return New york)

Aucun commentaire:

Enregistrer un commentaire