0

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.start
st = gets.stop
puts st

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Is "$" not making a instance variable? I could have sworn "@" made a global. And how do I create a "Timer instance"? you should also note i'm a complete newbie so if i sound like one its cause i am :)
@bipolarpants: You have it backwards. @foo is an instance variable, $foo is a global. And don't worry about being new — everyone is at some time or another.
oh ok cool, thanks. Now I got it to work but I had to create a method in the String class "class String def to_t Timer.new end" and then add it to "s = gets.to_t.start" like that. is there any way around this?
and sorry for the terribly written format of that last comment I couldn't seem to hit "enter" without it sending the comment :/
@bipolarpants: Instead of calling start and stop on the string, create a Timer and call the methods on that. Just create it in the method where you want it.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.