【问题标题】:Is there a way to shorten a long elsif statement in Ruby? [duplicate]有没有办法缩短 Ruby 中长长的 elsif 语句? [复制]
【发布时间】:2020-04-06 05:20:14
【问题描述】:

有没有办法缩短这段代码并减少重复?

puts "Which type of pokemon would you like to see the strengths for?"
type = gets.chomp
puts "Ah a #{type} type!"

if type.downcase == "normal"
  puts "Normal pokemon are not strong against any other type in particular. Too bad :("
elsif type.downcase == "fighting"
  puts "Fighting pokemon are strong against normal, rock, steel, ice, and dark types."
elsif type.downcase == "flying"
  puts "Flying pokemon are strong against fighting, bug, and grass types."
elsif type.downcase == "poison"
  puts "Poison pokemon are strong against grass and fairy types." 

等等……

【问题讨论】:

    标签: ruby if-statement


    【解决方案1】:

    您可以使用case 声明:

    case type.downcase
    when "normal"
      puts "Normal pokemon are not strong against any other type in particular. Too bad :("
    when "fighting"
      puts "Fighting pokemon are strong against normal, rock, steel, ice, and dark types."
    when "flying"
      puts "Flying pokemon are strong against fighting, bug, and grass types."
    when "poison"
      puts "Poison pokemon are strong against grass and fairy types." 
    end
    

    如果您愿意,可以将 puts 移到 case 语句之外

    puts case type.downcase
         when "normal"
           "Normal pokemon are not strong against any other type in particular. Too bad :("
         when "fighting"
           "Fighting pokemon are strong against normal, rock, steel, ice, and dark types."
         when "flying"
           "Flying pokemon are strong against fighting, bug, and grass types."
         when "poison"
           "Poison pokemon are strong against grass and fairy types." 
         end
    

    【讨论】:

      【解决方案2】:

      您可以将值放在哈希中:

      types = {
           "normal" => "Normal pokemon are not strong against any other type in particular. Too bad :(",
           "fighting" => "Fighting pokemon are strong against normal, rock, steel, ice, and dark types.",
           "flying" => "Flying pokemon are strong against fighting, bug, and grass types.",
           "poison" => "Poison pokemon are strong against grass and fairy types." 
          }
      
      puts "Which type of pokemon would you like to see the strengths for?"
      type = gets.chomp
      puts "Ah a #{type} type!"
      
      puts types[type.downcase]
      

      您还可以为哈希设置默认值,因此当输入不存在的类型时,它将显示默认消息:

      types = Hash.new("Type does not exist")
      types.merge!(h)
      

      【讨论】:

      • 也可以用#fetch(type.downcase, 'type does not exist') 解决以避免默认值:)
      • @AlexGolubenko 不错!
      猜你喜欢
      • 1970-01-01
      • 2014-10-19
      • 1970-01-01
      • 2013-05-25
      • 2021-07-30
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多