Skip to content

Instantly share code, notes, and snippets.

@eljojo
Last active December 1, 2024 20:35
Show Gist options
  • Save eljojo/ddb1257886a5267eab6620d493f61f98 to your computer and use it in GitHub Desktop.
Save eljojo/ddb1257886a5267eab6620d493f61f98 to your computer and use it in GitHub Desktop.
calling IRB from ruby
require 'irb'
IRB.init_config(nil)
IRB.conf[:PROMPT_MODE] = :DEFAULT
IRB.conf[:VERBOSE] = true
class IrbStringInputMethod < IRB::InputMethod
def initialize(line, output)
@line = line
@read = false
@output = output
end
def gets
return nil if @read
@output << prompt
@read = true
@line
end
def encoding
Encoding.default_external
end
end
script = "1 + 1\n"
old_stdout , string_out = $stdout, StringIO.new
io = IrbStringInputMethod.new(script, string_out)
irb = IRB::Irb.new(nil, io)
$stdout = string_out
irb.eval_input
$stdout = old_stdout
puts string_out.string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment