IRB analogue of python -i
Asked Answered
S

1

9

I want to use IRB to run a script then give me an interactive prompt. I do this with python -i xy.py in Python, however irb xy.rb exits after execution.

> python --help

-i    When a script is passed as first argument or the -c option is
      used, enter interactive mode after executing the script or the
      command
Slothful answered 22/1, 2011 at 11:39 Comment(0)
A
10
irb -r xy.rb

It simply requires the file mentioned before giving you a normal IRB prompt.

Abscise answered 22/1, 2011 at 11:42 Comment(6)
Keep in mind though, that using -r or require will not give you access to the local variables of the script, even if they are defined at the top-level execution environment.Hurley
@hso It's because of ruby's scoping rules. When you require or load a file in ruby, local variables at the top level of that file do not "spill out" (i.e. aren't accessible) of that script. This doesn't just apply to irb, but also when one script requires another. You could use eval to get around this, but then you'd need to mess with bindings...Hurley
Btw, starting with ruby 1.9, you need to prepend the path to the required file: irb -r ./xy.rbHurley
@hso if you want access to the external script's locals, you should look into using a debugger. See related questionHurley
Thanks, @Kelvin. I have never used Ruby seriosly. I'm used to how Python imports work and trying to wrap my head around this.Sapient
@Sapient Even with python, variables in an imported file don't pollute the current namespace unless you ask it to via from lib import X. If you do a plain import lib, you could still access variables via lib.some_variable. Ruby doesn't allow this; it only brings in globals ($-prefixed), class-vars (@@-prefixed), instance-vars (@-prefixed), constants (including classes & modules) and methods. But they always get pulled in at the top-level, not namespaced by the file that contains them.Hurley

© 2022 - 2024 — McMap. All rights reserved.