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
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465

1 Answers1

10
irb -r xy.rb

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

Ashley Williams
  • 6,770
  • 4
  • 35
  • 42
  • 4
    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. – Kelvin Jan 29 '13 at 16:44
  • @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 `require`s another. You could use `eval` to get around this, but then you'd need to mess with bindings... – Kelvin Jul 02 '14 at 17:46
  • 2
    Btw, starting with ruby 1.9, you need to prepend the path to the required file: `irb -r ./xy.rb` – Kelvin Jul 02 '14 at 17:47
  • @hso if you want access to the external script's locals, you should look into using a debugger. See [related question](http://stackoverflow.com/q/1144560/498594) – Kelvin Jul 02 '14 at 17:54
  • Thanks, @Kelvin. I have never used Ruby seriosly. I'm used to how Python imports work and trying to wrap my head around this. – hso Jul 02 '14 at 17:57
  • @hso 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. – Kelvin Jul 02 '14 at 18:07