Master IRB in Ruby: Explore and Test Code Interactively

Table of Contents

Introduction

Mastering IRB in Ruby makes coding faster, clearer, and more interactive. IRB, or Interactive Ruby, is a built-in command-line tool that lets developers write, test, and debug Ruby code in real time without creating separate files. By running code line by line, programmers can instantly view return values, load libraries, and refine scripts efficiently. This guide explores how to use IRB for hands-on coding, gem testing, and customizing your Ruby environment for smoother development.

What is Interactive Ruby (IRB)?

Interactive Ruby, or IRB, is a tool that lets people test and explore Ruby code directly without needing to create separate files. It provides an instant environment where users can type Ruby commands, see results right away, and experiment with different ideas. IRB helps beginners and developers understand how Ruby works by allowing quick feedback, easy debugging, and customization with saved history and shortcuts. It makes learning and testing Ruby simpler and faster in a hands-on way.

Starting and Stopping IRB

So, you’ve got Ruby installed, right? That means you already have access to IRB, short for Interactive Ruby. Think of IRB as your personal Ruby playground, a place where you can talk directly to the Ruby interpreter and see what it says back. It’s kind of like having a casual chat with Ruby itself.

You can start it up on any computer that has Ruby installed by typing:

$ irb

Once you hit enter, boom, you’re greeted by that friendly little IRB prompt:

Output
irb(main):001:0>

That prompt right there is Ruby’s way of saying, “Hey, I’m ready! What do you want to do?” Every command or line of code you type runs in what’s called the main context, which is the top-level scope of a Ruby program. The number you see keeps track of your commands, kind of like Ruby’s way of numbering your thoughts.

Now, if you’ve installed Ruby using RVM (that’s Ruby Version Manager), don’t be surprised if your prompt looks a bit different, maybe something like:

Output
2.4.0 :001 >

That just means Ruby is giving you a bit more info, like which version it’s using. But if you prefer a cleaner, simpler prompt (you know, less clutter, more focus), you can start IRB with this:

$ irb –prompt inf-ruby

Once you’re inside IRB, the fun begins. You can type actual Ruby code right into it, no need to create a whole file first. For example, let’s do something simple like math. Try typing this:

2 + 2

When you press ENTER, IRB answers almost instantly:

Output
=> 4

That little => is Ruby’s way of saying, “Here’s what I got for you.” It’s the return value of your expression, the result of whatever you just asked it to do.

When you’re done and ready to wrap things up, you can leave IRB by typing:

$ exit

or pressing CTRL+D . That’ll take you back to your regular command line.

See? Starting and stopping IRB is as easy as chatting with a buddy. Now that you know how to open the conversation, let’s see what you can actually do with it by running some hands-on Ruby code.

Executing Code in an IRB Session

Alright, picture this. You’ve just opened IRB, and now it’s time to experiment. IRB is basically your Ruby test lab, the perfect spot to check if your code does what you think it should. And here’s something cool, in Ruby (and IRB), everything gives back a value. Yep, even the simplest thing you type will show you a result right away.

Let’s try it out with a classic:

puts “Hello World”

Press ENTER, and here’s what happens:

Output
Hello World
=> nil

The first part, “Hello World,” is what the puts method prints on your screen. It’s Ruby waving back at you. But that => nil part? That’s Ruby quietly saying, “Hey, every method returns something.” In this case, puts gives back nil, which basically means “nothing to see here.”

Every time you type a new command, IRB updates the line number:

Output
irb(main):001:0> puts “Hello World”
Hello World
=> nil
irb(main):002:0>

That’s super helpful when you’re checking your own code or tracking down bugs.

Now, let’s have a bit of fun with variables. Try this:

birth_year = 1868

When you hit ENTER, IRB shows you:

Output
=> 1868

It’s saving your data and confirming it at the same time. Next, add a couple more variables:

death_year = 1921
age_at_death = death_year – birth_year

And what do you get back?

Output
=> 53

There you go, Ruby just did the math for you.

Here’s where IRB really gets handy. It can handle multi-line code, too. Let’s say you want to test a block of code that filters an array. Type this in line by line:

[“Tiger”, “Great White”, “Angel”].select do |shark|
  shark.include?(“a”)
end

As you’re typing, you’ll notice IRB adds a * and a new scope level in the prompt, like this:

Output
irb(main):005:0> [“Tiger”, “Great White”, “Angel”].select do |shark|
irb(main):006:1* shark.include?(“a”)
irb(main):007:1> end
=> [“Great White”]

Pretty cool, right? It’s like having a live coding notebook. You can test ideas, play with methods, and see results right away, all without creating a separate .rb file.

Using Libraries and Gems

Now, this is where IRB gets even more fun. It’s not just for quick tests, it’s also a great place to play with Ruby’s huge library of built-in tools and gems. With a simple require statement, you can bring in just about anything you need.

Let’s start with something built right into Ruby, Net::HTTP . Type this:

require ‘net/http’

If it works, IRB will reply:

Output
=> true

Now, let’s use it for something interesting, like getting your external IP address from a simple site:

uri = URI.parse(“http://icanhazip.com”)
response = Net::HTTP.get_response uri
response.body

Here’s what you’ll see:

Output
irb(main):010:0> uri = URI.parse(“http://icanhazip.com”)
=> #<URI::HTTP http://icanhazip.com>
irb(main):011:0> response = Net::HTTP.get_response uri
=> #<Net::HTTPOK 200 OK readbody=true>
irb(main):012:0> response.body
=> 203.0.113.52\n

Pretty slick, right? But sometimes things don’t go perfectly. For example, if you try to load a library that’s not installed yet:

require ‘httparty’

Ruby will respond:

Output
LoadError: cannot load such file — httparty

That’s just Ruby’s polite way of saying, “Hey, I don’t have that one.” To fix it, exit IRB (type exit or press CTRL+D) and run:

$ gem install httparty

Once that’s done, start IRB again:

$ irb

Now when you load it:

require ‘httparty’
Output
=> true

You’re all set. Try getting your IP again using HTTParty:

response = HTTParty.get(“http://icanhazip.com”)
response.body
Output
=> 203.0.113.52\n

Loading Your Code into IRB

Here’s a neat trick. You can load your own Ruby code right into IRB. Let’s say you start IRB with the -r switch. That lets you automatically load libraries or files when you start. For example:

$ irb -r httparty

That saves you from typing require 'httparty' each time.

Now, imagine you’ve written a small Ruby script called ip_grabber.rb . It looks like this:

require ‘httparty’
class IPGrabber
  def initialize()
    @url = “http://icanhazip.com”
  end  def get
    response = HTTParty.get(@url)
    response.body.chomp # remove the \n if it exists
  end
end

This class is your little Ruby helper. It goes online, gets your IP address, and cleans up the result. Simple, clean, and effective. To use it in IRB, save the file and load it like this:

$ irb -r ./ip_grabber

Then try it out:

ip = IPGrabber.new
ip.get
Output
=> 203.0.113.52

Customizing IRB

Alright, here’s the best part about IRB, making it your own. You can tweak it using a file called .irbrc . Think of it like IRB’s notebook. It remembers your favorite settings, shortcuts, and small custom touches.

Open it in your home directory:

$ nano ~/.irbrc

Want autocompletion? Just add this:

require ‘irb/completion’

Now, when you hit TAB, IRB fills in variable names, methods, or objects for you. It’s super handy when you’re coding fast.

Next, make IRB remember your past commands:

IRB.conf[:SAVE_HISTORY] = 1000

That saves your last 1,000 commands in a file called .irb_history . When you reopen IRB, your command history is ready to scroll through with the Up and Down keys or search with CTRL+R.

Want to use a different history file? You can:

IRB.conf[:HISTORY_FILE] = ‘~/your_history_filename’

And if you want your code to look cleaner, you can turn on auto-indentation:

IRB.conf[:AUTO_INDENT] = true

But here’s where it gets fun, you can write Ruby code inside .irbrc too. For instance, say you want to make a helper that shows your command history:

def history
  history_array = Readline::HISTORY.to_a
  print history_array.join(“\n”)
end

Want to make it a bit fancier? Try this version that limits how many entries you see:

# history command
def history(count = 0)
  history_array = Readline::HISTORY.to_a
  count = count > 0 ? count : 0
  if count > 0
    from = history_array.length – count
    history_array = history_array[from..-1]
  end
  print history_array.join(“\n”)
end

Now, when you type history 2 , you’ll only see your last two commands.

Loading too many libraries at startup can slow things down. It’s best to load only what you need, when you need it.

With all these tweaks, IRB becomes your own Ruby workspace, flexible, quick, and friendly. It’s like having a coding partner that’s always ready to help you test, learn, and build.

Ruby IRB Official Documentation

Conclusion

Mastering IRB in Ruby empowers developers to test, debug, and refine their code with instant feedback and flexibility. By experimenting directly in the Ruby interpreter, programmers can explore ideas faster, test gems, and customize their coding environment for better efficiency. Whether you’re refining logic, loading libraries, or exploring custom scripts, IRB provides a safe, hands-on space to enhance your Ruby skills. As Ruby continues to evolve, mastering tools like IRB will remain essential for rapid development and interactive programming in modern workflows.

Master Ruby Comments: Write Clear and Readable Code (2025)

Caasify
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.