Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did I get "main.using is permitted only at toplevel" when I used a Refinement in IRB?

I tried to use a Refinement in IRB (v0.9.6, Ruby 2.3.0):

module Foo
  refine Object do
    def foo() "foo" end
  end
end

using Foo # => RuntimeError: main.using is permitted only at toplevel

This is basically the exact setup from the documentation (which results in the same error).

What went wrong? How do I fix this?

like image 215
user513951 Avatar asked Jan 05 '16 20:01

user513951


1 Answers

It's either a bug or a misfeature of IRb. It is well-known that due to the pretty hackish way IRb is implemented, it does not behave correctly for all corner-cases.

The incompatibility probably everybody knows is that in Ruby, methods defined at the top-level become private instance methods of Object, whereas in IRb, they become public instance methods of Object. Another obvious behavioral difference is that in IRb, require_relative doesn't work, because it searches relative to the current file, but in IRb, there is no current file.

There are also some differences in what syntax gets accepted, I believe, and something to do with local variables and when exactly they are and aren't defined.

So, it is not inconceivable that there might also be some behavioral differences wrt. Refinements. In fact, I myself have encountered that error message, and running the exact same code outside IRb, either with ruby -e, from a file, or from a different REPL, always made it go away.

like image 153
Jörg W Mittag Avatar answered Nov 10 '22 14:11

Jörg W Mittag