所以即时尝试在ruby中编写一个简单的定时器程序。我在“Timer”类中定义了我的方法,但是当我调用它们时,它给了我一个NoMethodError。任何想法为什么?谢谢您的帮助。在一个类中创建一个方法并在Ruby中使用它
require "Time"
class Timer
def start
$a = Time.now
end
def stop
Time.now - $a
end
end
puts "Type in 'Start'to to start the timer and then type 'Stop' to stop it"
s = gets.start
st = gets.stop
puts st
“$”没有创建实例变量?我可以宣誓“@”成为全球性的。我该如何创建一个“Timer实例”?你也应该注意到我是一个完整的新手,所以如果我听起来像一个其原因,我:) – 2010-10-08 22:14:46
@bipolarpants:你有它倒退。 '@ foo'是一个实例变量,'$ foo'是一个全局变量。不要担心新事物 - 每个人都在某个时间或另一个时间。 – Chuck 2010-10-08 22:59:32
哦好吧,谢谢。现在我得到它的工作,但我不得不在String类中创建一个方法“class String def to_t Timer.new end”,然后将它添加到“s = gets.to_t.start”那样。有没有办法解决? – 2010-10-09 01:51:17