1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

DEPARTUREAdvent Calendar 2023

Day 2

色々な言語で簡単なREPLを実装する #ruby

Last updated at Posted at 2023-12-02

REPLとは

REPLとは、Read-Eval-Print Loopの略で、プログラミング言語の実行環境の一つです。ユーザーが入力欄にキーボードなどから式や文を一行入力(Read)、即座に評価(Evaluate)して結果を返し(Print)、再び入力可能(Loop)になる対話的な実行方式です。

Rubyで実装する

main.rb

def main
  while true
    begin
      print "ruby> "

      input = STDIN.gets
      raise Interrupt if input.nil?

      prompt = input.chomp
      break if prompt == "exit"

      # puts eval(prompt)
      puts prompt
    rescue Interrupt
      puts "\nBye!"
      break
    rescue Exception
      puts "Error: #{$!}"
    end
  end
end

main

実行する

$ ruby main.rb
ruby> 1 + 1
1 + 1
ruby> foobar
foobar
ruby> ^D
Bye!

puts promptの部分でevalをすると、1 + 1など計算式が評価された結果を出力できます。
この部分は今後の各言語による実装でも同様にしています。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?