Interactive Ruby Shell
Learn the Interactive Ruby Shell.
We'll cover the following
One other tool that’s worth mentioning and that comes with Ruby runtime is IRB. We can start it by typing irb
in the shell and hitting “Enter.”
Its name is short for Interactive Ruby Shell, and yes, it’s another kind of shell. Just like the shell running in the terminal, irb
is also a program that interactively waits for us to type something and hit “Enter.” However, because this is a Ruby shell, it expects that we type Ruby code instead of system commands.
Remember: IRB is pretty handy for quickly trying something out, and it’s a great tool for exploring the Ruby language and things that come built in.
For example:
$ irb> puts "Hello world!"Hello world!=> nil>
The first line starts the IRB program. Notice how the “prompt” indicator changes. The prompt looks a little different depending on your system and shell configuration, but $
is often used to indicate that this is a system shell prompt, while >
is used by IRB to indicate that this is an interactive Ruby shell.
The second line is a piece of Ruby code. When we type this line and hit “Enter,” Ruby executes the code and prints out the text “Hello world!”
It then also prints out the return value for this statement, which in this case is nil
. The rocket (=>
) indicates that a value is being returned by the executed statement.
Notice the IRB again waiting for input with a prompt in the last line.
We can exit the IRB session and get back to our system shell by typing exit
and hitting “Enter.” You can also just hit “ctrl-d”, which does the same thing.
Ruby runtime
The last tool we need is a Ruby runtime. This is a program that can execute Ruby code and can be run in the shell (much like cd
and ls
).
If we have some code in a file with the name hello.rb
and we’ve navigated to the directory where the file is saved, then we can type the following and hit “Enter” to execute the code:
ruby hello.rb
This tells the ruby
runtime to interpret the contents of the file hello.rb
as Ruby code and execute it.
We can also use this program to do other things. We probably won’t need these often, but they’re good to know. We can try these by typing these commands in the terminal.
For instance, we can print out the version of the program:
ruby --version
Or, we can execute Ruby code without storing it in a file:
ruby -e 'puts 123'