Reputation: 3046
i'm using irb -I . -r script.rb
to require
a script before starting an interactive session. functions defined in the global scope are available but variables aren't unless they are declared with @
is there a way to access local variables defined in the global context of a script or a better way to do this
script.rb:
def func() "..." end
a = "str"
@b = 1
then after irb
starts:
irb(main):001:0> a
NameError: undefined local variable or method `a' for main:Object
from (irb):1
from /usr/bin/irb:11:in `<main>'
irb(main):002:0> @b
=> 1
irb(main):003:0> func
=> "..."
i'm assuming that the script's contents are executed as if defined in a function (eg: main
in C-type languages) and so the variables at the global context are local variables that are not accessible outside that scope
so do most people use @
variables when writing their scripts?
the use-case is narrow in scope (script development) and the solution is trivial (search-replace any variable
with @variable
), but I'm learning the semantics of the language and I'm curious about this. Can't the execution context be exposed and merged into the current context somehow?
Upvotes: 0
Views: 348
Reputation: 11
Maybe binding.irb
is what you are looking for.
script.rb:
def func() "..." end
a = "str"
@b = 1
binding.irb
From the documentation:
Opens an IRB session where binding.irb is called which allows for interactive debugging. You can call any methods or variables available in the current scope, and mutate state if you need to.
Upvotes: 1
Reputation: 369556
No. You can't access local variables from a different scope. That's the whole point of local variables: they are local to the scope they are defined in.
In this case, a
is local to the script body of script.rb
.
Upvotes: 3