Last active
December 1, 2024 20:35
-
-
Save eljojo/ddb1257886a5267eab6620d493f61f98 to your computer and use it in GitHub Desktop.
calling IRB from ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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