Home > Back-end >  Why this simple ruby code does not work in the commandline, but does when pasting it in irb
Why this simple ruby code does not work in the commandline, but does when pasting it in irb

Time:11-15

I have the following code:

sample_code.rb

class Foo
  def bar
    Timeout.timeout(0.5){
        puts "Interupt this if it takes longer then 0.5 seconds"
    }
  end
end

foo = Foo.new()
foo.bar

The example above works when you paste it in irb, but when you place it in a script and run it like this:

ruby ./sample_code.rb

It will give the following error.

Traceback (most recent call last):
        1: from ./irb_works_ruby_dont.rb:11:in `<main>'
./irb_works_ruby_dont.rb:4:in `bar': uninitialized constant Foo::Timeout (NameError)

Is this a Timeout issue? Does irb load some modules that the normal ruby command doesn't? How to make the code work when run as a script?

CodePudding user response:

The most likely explaination is that IRB requires Timeout when it starts up the REPL - but your script file is being executed before that happens. You can fix it by simply requiring it:

require 'timeout'

class Foo
  def bar
    Timeout.timeout(0.5){
        puts "Interupt this if it takes longer then 0.5 seconds"
    }
  end
end

foo = Foo.new
foo.bar
  • Related