- Read Tutorial
- Watch Guide Video
In this guide we are going to walk through a basic introduction to the IRB console. The word IRB stands for Interactive Ruby Console or Interactive Ruby shell, and it allows you to run Ruby code at the command line interface. For example, when you use irb, you can directly run code like this.
That was a simple one. Now, what happens when you want to execute more complex code?
Let's pull out a code from a basic Ruby lesson.
puts "What is your name?" name = gets.chomp puts "Hello " + name + " how are you?"
When you execute it, the output will look pretty like this:
What happens when we open irb and do the same thing. Let's open irb and copy the code line by line.
In this case, the subsequent lines don't run because we haven't asked it to run yet.
What really happened is we asked irb to call the puts
method with an argument, and it did exactly that. The "nil" value that you see just means that puts
method did not return anything.
To keep going, let's copy and paste the next line in our terminal.
It may look like nothing is happening, but it's actually waiting for us to respond. When we executed the file earlier, it was more intuitive as there was a question and we responded. Here, it's waiting for us to respond because we are calling the code line by line. Now, if I type in my name, it's going to return it back to me like this:
This is because the name
variable now has the value Jordan
.
Next, if we print the last line, our output will be:
Again, there was a nil value because the method puts
did not return anything. To end the irb session, we hit ctrl + d
.
So, that's how it works. Hopefully, this should give you an idea of what happens in irb versus what happens when you execute a code file. These differences are significant especially when you want to get inputs from users.