REPL

Learn to execute Ruby programs in the Ruby interactive shell called `irb`, and learn how to run a program from a file.

Hello, I’m your REPL

In the case of the 1 + 1 program from the previous chapter, the interpreter performs two actions: read ® and evaluate (E). We used no “print” action (puts in our case), so no result was displayed on the screen. In other words, to see the results we need to perform these three actions:

  • Read (R)
  • Evaluate (E)
  • Print (P)

It would also be nice if we could avoid running the ruby command from the terminal every time, so that we can execute programs in a constant loop (L). It turns out that this functionality is already there! The REPL acronym stands for Read Evaluate Print Loop.

It’s very similar to the Ruby interpreter, but differs in that it accepts the “Enter” key as the end of our program. Instead of exiting on Ctrl+D, signifying end of input, it just starts reading the input again. REPL is a well-known acronym, which is not tied to the Ruby language infrastructure. Other languages have their own REPLs too. Ruby’s REPL is called irb. We can type this command from our shell:

$ irb
2.5.1 :001 >

The numbers at the beginning of the line are just indicators of the Ruby version we’re using, such as (2.5.1). The same output is produced when the ruby -v command is run. 001 indicates the first string. In the future, we’ll see how we can type multiline mini-programs to REPL. Since the REPL acronym already contains the word “print” in it, we don’t need to type puts. Regardless of what we do, the result will be printed on our screen.

The principle of least surprise says that to exit REPL, we should type exit. Let’s do that now to see if it works.

Authors rarely use the default irb as a REPL. There is a better alternative called Pry. It has the same functionality, but offers more flexibility and room for configuration.

Get hands-on with 1200+ tech skills courses.