如何在Ruby中将磅转换为kg?

时间:2015-05-25 18:35:15

标签: ruby-on-rails ruby

当我在Ruby中运行下面的代码时,我收到一条错误消息:ex5.rb:3:in '< main >': undefined local variable or method 'cm' for main:Object < NameError >

我做错了什么?

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

2 个答案:

答案 0 :(得分: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."

这似乎工作正常。

答案 1 :(得分:0)

Ruby中的变量只能在声明后引用。尝试移动变量&#34; height&#34;低于&#34; cm&#34;。同样,你应该放置&#34; weight&#34;低于&#34; kg&#34;。

相关问题