Skip to content

Instantly share code, notes, and snippets.

@radarek
Last active August 3, 2023 21:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radarek/066307b304d18985b7c6 to your computer and use it in GitHub Desktop.
Save radarek/066307b304d18985b7c6 to your computer and use it in GitHub Desktop.

What is the problem?

How to execute file in irb/pry session and use its local variables.

https://www.reddit.com/r/ruby/comments/43nlxh/how_do_you_read_commands_from_file_in_a_pry/

IRB

$ irb
irb(main):001:0> foo
NameError: undefined local variable or method `foo' for main:Object
	from (irb):1
	from /Users/radarek/.rbenv/versions/2.3.0/bin/irb:11:in `<main>'
irb(main):002:0> IRB.conf[:MAIN_CONTEXT].workspace.binding.eval File.read("./foo.rb")
=> nil
irb(main):003:0> foo
=> "local variable from foo.rb file"

Pry

$ pry
[1] pry(main)> foo
NameError: undefined local variable or method `foo' for main:Object
from (pry):1:in `__pry__'
[2] pry(main)> Pry.toplevel_binding.eval File.read("./foo.rb")
=> nil
[3] pry(main)> foo
=> "local variable from foo.rb file"
foo = "local variable from foo.rb file"
nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment