开发者

Creating a method in a class and using it in Ruby

开发者 https://www.devze.com 2023-01-19 12:27 出处:网络
so im trying to write a simple timer program in ruby. I defined my methods in a \"Timer\" class but when I call them it gives me a NoMethodError. Any ideas why? Thanks for the help.

so im trying to write a simple timer program in ruby. I defined my methods in a "Timer" class but when I call them it gives me a NoMethodError. Any ideas why? Thanks for the help.

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.st开发者_如何学编程art
st = gets.stop
puts st


You're sending start and stop to the return value of gets, which is a String, not a Timer.

Also, you should use instance variables rather than globals to hold the timer value. And you'll also need to create a Timer instance (or turn Timer into a module, but use an instance variable even then, not a global).


Looks like you're not initialising a class object. So either you need to have an initialise method or you can reference the class in the methods.

eg

class Timer

 def self.start
    $a = Time.now
 end

 def self.stop
    Time.now - $a
 end


end
0

精彩评论

暂无评论...
验证码 换一张
取 消