Ruby程序没有按预期执行?如果条件失败,则执行块

时间:2017-08-30 13:24:33

标签: ruby if-statement

以下程序旨在迭代holiday_hash,将所有键和值大写并将其输出:

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

预期的输出格式为:

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

holiday_hash如下:

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

问题是:

  1. 即使条件无法评估为真,if块也会执行。
  2. 需要的建议:

    1. 如何简化大写符号的过程,这些符号中包含两个单词:new_york可以大写到纽约? (因为#capitalised方法将返回纽约)

1 个答案:

答案 0 :(得分:4)

  

即使条件无法评估为if

true块也会执行

让我们看看:

key2 = :new_year
key2 == :new_year || :fourth_of_july || :memorial_day
#=> true

现在是一个应该返回false的键:

key2 = :thanksgiving
key2 == :new_year || :fourth_of_july || :memorial_day
#=> :fourth_of_july

这不是您的预期结果,但您的假设也不正确:if块的执行只是因为条件总是 truthy

为什么呢?因为它相当于:

false || :fourth_of_july || :memorial_day
#=> :fourth_of_july

你想:

key2 == :new_year || key2 == :fourth_of_july || key2 == :memorial_day
#=> false

或者更短一些:

[:new_year, :fourth_of_july, :memorial_day].include? key2
#=> false
  

如何简化在其中包含两个单词的符号的大写过程[...]

我通过下划线splitcapitalize每个单词join结果:

:new_year
  .to_s              #=> "new_year"
  .split('_')        #=> ["new", "year"]
  .map(&:capitalize) #=> ["New", "Year"]
  .join(' ')         #=> "New Year"

我已将方法调用分开以显示中间结果。您可以在上面写一行:

:new_year.to_s.split('_').map(&:capitalize).join(' ')
#=> "New Year"