变量未定义

时间:2014-02-01 00:12:41

标签: ruby variables

我正在玩弄试图理解它的东西,它说的是

:/Ruby Tutorials/dragonhealth.rb:9:in `<main>': undefined local variable or met
od `toughness' for main:Object (NameError)

我无法弄清楚为什么变量没有被定义。它接受来自gets.chomp.to_i的输入就好了这条线,看起来非常简单,正在破坏它

health + armor = toughness


def dragon_toughness(health, armor)
puts "The dragon's health is #{health}!"
puts "The dragon's armor is #{armor}!"
end
puts "What is the dragon's health?"
health = gets.chomp.to_i
puts "What is the dragon's armor?"
armor = gets.chomp.to_i

health + armor = toughness

dragon_toughness(health, armor)

if toughness > 40
puts "Wow, tough dragon!"
elsif
    toughness <= 40
puts "That dragon is kinda weak son!"

end

1 个答案:

答案 0 :(得分:2)

更改行

  health + armor = toughness

as

  toughness = health + armor

完整代码(粘贴在我的文件so.rb中):

def dragon_toughness(health, armor)
  puts "The dragon's health is #{health}!"
  puts "The dragon's armor is #{armor}!"
end

puts "What is the dragon's health?"
health = gets.chomp.to_i
puts "What is the dragon's armor?"
armor = gets.chomp.to_i

toughness = health + armor

dragon_toughness(health, armor)

if toughness > 40
  puts "Wow, tough dragon!"
elsif
  toughness <= 40
  puts "That dragon is kinda weak son!"  
end

让我们运行它:

(arup~>Ruby)$ ruby so.rb
What is the dragon's health?
12
What is the dragon's armor?
13
The dragon's health is 12!
The dragon's armor is 13!
That dragon is kinda weak son!
(arup~>Ruby)$