2015-05-25 59 views
1

當我在Ruby中運行下面的代碼時,出現如下錯誤:ex5.rb:3:in '<main>': undefined local variable or method 'cm' for main:Object <NameError>如何在Ruby中將磅轉換爲kg?

我在做什麼錯了?

name = 'Chris Hanson' 
height = 60 * cm 
cm = 2.54 
weight = 180 % kg 
kg = 2.2 
eyes = 'Brown' 
teeth = 'White' 
hair = 'Black' 

puts "Let's talk about #{name}." 
puts "He's #{height} cm tall." 
puts "He's #{weight} kg heavy." 
puts "He's got #{eyes} eyes and #{hair} hair." 
puts "His teeth are usually #{teeth} depending on the coffee." 

回答

3

這裏的錯誤在使用它們之前沒有聲明變量。看看我使用的訂單('cm'和'kg'變量):

name = 'Chris Hanson' 
cm = 2.54 
height = 60 * cm 
kg = 2.2 
weight = 180 % kg 
eyes = 'Brown' 
teeth = 'White' 
hair = 'Black' 

puts "Let's talk about #{name}." 
puts "He's #{height} cm tall." 
puts "He's #{weight} kg heavy." 
puts "He's got #{eyes} eyes and #{hair} hair." 
puts "His teeth are usually #{teeth} depending on the coffee." 

這似乎工作正常。

+0

非常感謝! – Ellen

0

Ruby中的變量只能在聲明它們後才能引用。嘗試移動「cm」下面的變量「height」。同樣,你應該把「重量」放在「kg」以下。