Wednesday, November 07, 2018

Developing REPL from Scratch in Ruby

Read Evaluate Print Loop

One liner:

loop { p eval gets }

Readable:

loop do
  print "$ "
input = gets.chomp!
result = eval(input)
puts "=> #{result}"
end


Persist Local Variable

myirb_binding = binding()
loop do
  print "$ "
input = gets.chomp!
result = myirb_binding.eval(input)
puts "=> #{result}"
end

Code written by Chris Wanstrath:

loop do
  print ENV['REPL_PROMPT'] || "#{ARGV[0]}>> "

  begin
    line = $stdin.gets.chomp
  rescue NoMethodError, Interrupt
    exit
  end

  if from_stdin
    run = "echo \"%s\" | #{command}" % [ line, nil ]
  else
    run = "#{command} %s" % [ line, nil ]
  end
  puts "$ #{run}" if debug
  system run
  warn "Use Ctrl-D (i.e. EOF) to exit" if line =~ /^(exit|quit)$/
end