0

Is there a way to shorten this code and reduce repetition?

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." 

ect...

laurend7
  • 15
  • 2

2 Answers2

1

You could use case statement:

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

if you want you can move puts outside of case statement

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
Marcin Doliwa
  • 3,639
  • 3
  • 37
  • 62
0

You can put the values in a hash:

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]

You could also set a default value for the hash, so when a type that doesn't exist is entered, it would show a default message:

types = Hash.new("Type does not exist")
types.merge!(h)
Viktor
  • 2,623
  • 3
  • 19
  • 28