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

1

7

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?

Accountable answered 5/1, 2016 at 20:21 Comment(2)
It looks like a bug in irb to me. It works fine with pry. Also the error message does not have sense since we are calling using precisely on the top level.Seventieth
Check bugs.ruby-lang.org/issues/9580Nawab
D
7

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.

Donal answered 6/1, 2016 at 6:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.