How To Use IRB to Explore Ruby


IRB, quick for Interactive Ruby, is a way that is quick explore the Ruby programming language and try out code without creating a file. IRB is a Read-Eval-Print Loop, or REPL, a tool offered by many programming that is modern. Theirb executable and type your Ruby code at the prompt to use it, you launch. IRB evaluates the code you type and displays the total outcomes.

IRB provides you with use of all Ruby’s integral features, including any libraries or gems you have set up. Besides, you’ll configure IRB to save lots of your demand history and auto-completion that is even enable of rule.

In this guide, you will make use of IRB to perform some rule, examine its production, make outside libraries, and modify your IRB session.

Starting and Stopping IRB

If you’ve got Ruby set up, you will have IRB. It can be started by you on any computer in which Ruby is set up by performing the demand irb from your own demand line screen.

You'll be greeted utilizing the IRB ( that is prompt***************)

IRB session


The prompt suggests you are operating IRB which what you perform will run in main context, which will be the top-level standard context of a Ruby system. It shows a relative line quantity.

Note: if you have set up Ruby with RVM, your prompt may look somewhat various, showing the variation quantity alternatively:

IRB session from RVM

2.4.0 :001 >

To obtain the shown that is prompt this guide, launch IRB with irb --prompt inf-ruby.

IRB takes syntax that is ruby which you yourself can enter at prompt. Give it a shot by the addition of two figures together:

Press the ENTER key and IRB will reveal the end result:

IRB session

=> 4

The => icon tells you this could be the return value from Ruby phrase.

To exit IRB, kind exit at prompt, or press CTRL+D. You will come back to your shell prompt.

Let's dig some much deeper into IRB by taking a look at tips on how to put it to use to explore rule.

Executing Code in an IRB Session

IRB is a way that is great try out code to see if it's a good solution to your problem. Almost everything in Ruby returns some value, and every right time you perform a statement in IRB, you will see that return value printed towards the display screen.

To show this, perform this declaration in a IRB that is new session***************)

whenever you click the ENTER key, you will see two outcomes from IRB:


Hi World => nil

The very first outcome could be the production from puts technique, which prints the sequence you specified, accompanied by a line break. The puts technique prints the written text towards the output that is standard, which will be your display screen. However the puts technique has a return value, because every technique in Ruby has a return value. The puts technique comes back nil, and that is exactly what IRB is showing you.

Every time you perform a declaration, the prompt modifications, showing a line that is new:

irb(primary):001:0> places "Hello World"
Hello World
=> nil

This will allow you to debug statements whenever doing more expressions that are complex an IRB session, as mistake communications will make reference to line figures.

You can designate values to factors in an IRB session exactly like you would inside standalone Ruby programs. Execute this declaration by typing it inside IRB session and pushing ENTER:

You'll begin to see the return value with this declaration echoed straight back:

IRB session

=> 1868

The adjustable birth_year holds this value, but, since many statements in Ruby return values, IRB teaches you the return value right here besides.

Add two more factors. First, create an adjustable called death_year:

Then create the adjustable age_at_death by subtracting birth_year from death_year:

  • age_at_death = death_year - birth_year

IRB assigns the worth towards the adjustable, and teaches you the end result:

IRB session

=> 53

if you are in an IRB session, it's not necessary to make use of an explicit puts or print declaration unless you wish to, because you'll see your return values presented.

Sometimes it is in addition crucial to compose rule that spans lines that are multiple. IRB supports this intuitively. IRB only executes code that is syntactically complete. The following Ruby code uses an array of sharks and uses the method that is select get back just the sharks containing the page "a" within their title. Type this rule into the IRB session, pushing ENTER after every relative line:

["Tiger", "Great White", "Angel"].select do |shark|

IRB enables you to enter numerous lines of rule, nonetheless it just executes the rule with regards to believes the rule is syntactically complete. Realize that the prompt modifications to point that IRB isn't yet assessing your rule by making use of an asterisk (*) and changing the last zero to a single to point a scope:( that is different***************)

IRB session

irb(primary):005:0> ["Tiger", "Great White", "Angel"].select do |shark| irb(primary):006:1* shark.include?("a") irb(primary):007:1> end

Since the line that is first the do keyword, IRB doesn't attempt to execute anything until it encounters the end keyword. Then it displays the total outcome:

IRB session

=> ["Great White"]

Using IRB, you can look at down components of rule to observe how they are going to work into your own programs before you incorporate them. You may also make use of IRB to work well with outside libraries.

Using Libraries and Gems

You can import libraries into the IRB session utilising the require declaration, in the same way you'd in a Ruby system. These libraries are things a part of Ruby's standard collection, things you have written your self, or gems, Ruby libraries distributed via that you simply install utilising the gem demand.

Ruby's standard collection includes modules in making internet needs and fetching the outcome. You can make use of those inside IRB session the same as you'd in a Ruby system.

Use the require declaration to import Net/HTTP from Ruby's standard collection. Enter the next distinct rule into your IRB session and press ENTER:

require 'net/http'

IRB suggests this declaration comes back true, which informs you your collection ended up being packed effectively. Now kind this rule into IRB in order to make a request to to fetch your IP address that is external:(***************)

uri = URI.parse("")
reaction = web::HTTP.get_response uri

(so you can debug each step:

As you enter each line, IRB shows you the return value,***************)

IRB session

irb(primary):010:0> uri = URI.parse("") => #<URI::HTTP> irb(primary):011:0> reaction = web::HTTP.get_response uri => #<Net::HTTPOK 200 okay readbody=true> irb(primary):012:0> reaction.body =>

If a collection could not be located, you will see a response that is different. Take to importing the HTTParty collection, making using HTTP needs some easier:

require 'httparty'

You'll see this message:

IRB session

LoadError: are unable to load such file -- httparty

This message informs you your libary you need is not available. HTTParty is distributed as a gem, therefore we are going to need to do the installation. Exit your IRB session with CTRL+D or kind exit to come back towards prompt. Then utilize the gem demand to set up the httparty treasure:

Now launch irb once more.

Try loading the module once more. This code:( in your IRB session, type***************)

require 'httparty`

This time, IRB will show true, helping you discover it had been in a position to load the collection. Enter this rule into IRB to ( try it out***************)

response = HTTParty.get("")

You'll begin to see the production printed towards the display screen:

IRB session


Now let us check how exactly to explore and test thoroughly your very own code that is ruby IRB.

Loading Your Code into IRB

If you begin an IRB session and make use of the -r switch, you'll specify libraries or gems you need to load whenever IRB begins. Including, irb -r httparty would introduce an IRB session utilizing the httparty treasure currently packed, meaning you'll miss the explicit require httparty declaration.

However, you may also utilize this to load your personal rule into a session that is new which will be helpful when you need to explore it or test drive it down.

Exit your IRB session by typing exit or by pushing CTRL+D.

Create a brand new Ruby file called ip_grabber.rb which describes a IPGrabber item with a get technique that, whenever supplied an Address, will get back the outside ip of device. We will utilize the HTTParty collection to fetch the reaction from We might utilize this IPGrabber item inside our very own system to protect our rule from outside modifications; utilizing our obect would let's replace the root collection and website we used to resolve the ip and never having to alter the way the sleep of our rule works.

Add this rule towards the file to determine the course:


require 'httparty'
course IPGrabber

  def initialize()
    @url = ""

  def get
    reaction = [email protected] that is.get(
    reaction.body.chomp  # eliminate the letter if it exists

Save the file and leave the editor.

Then launch IRB and load this file. As it's a file that is local than a treasure or an integral collection, we need to specify a path. We additionally won't need to specify the .rb expansion of file.

The IRB session lots, and you will begin to use this object that is new your session similar to this:

ip =

You'll see this production:

IRB session


By loading your personal rule into an IRB session, you'll examine rule and make use of your personal libraries before integrating them into a program that is full

Now you are aware how exactly to make use of rule in an IRB session, let us check how exactly to modify your IRB session.

Customizing IRB

You can cause a setup file called .irbrc that enables you to modify your IRB session. After that you can include help for autocompletion, indentation, and demand history.

Create this file in your house directory:

First, configure autocompletion help in IRB. This can enable you to utilize the TAB key to autocomplete item, adjustable names, and technique names in IRB:


require 'irb/completion'

Next, include help for saving your demand history to an file that is external


IRB.conf[:SAVE_HISTORY] = 1000

With this enabled, the final 1000 statements you kind is likely to be logged towards the .irb_history file in your house directory.

In addition, whenever you start a brand new IRB session, your history will load immediately, and you will utilize the Up and Down arrow secrets to go through these entries, or usage CTRL+R doing a search that is reverse exactly like you would in a Bash shell.

If you desired to specify a history that is different, include this towards setup file:


IRB.conf[:HISTORY_FILE] = '~/your_history_filename'

Next, include this line towards setup file allow auto-indenting, which will be handy whenever writing classes, practices, and obstructs:


IRB.conf[:AUTO_INDENT] = real

Your setup file may include any extra legitimate code that is ruby therefore you could determine helper practices or usage require to load extra libraries. Including, to incorporate a history helper towards IRB session which will show your history, include this rule to .irbrc:


def history
  history_array = Readline::HISTORY.to_a
  printing history_array.join("n")

whenever you load your IRB session, kind history to see your IRB history. You may possibly have a lot, so it takes an optional number of lines to show so you can alter the history command. Substitute the rule the history function using this rule, which takes an optional argument called count and makes use of it to restrict the entries it shows:


# history demand
def history(count = 0)

  # Get history into a wide range
  history_array = Readline::HISTORY.to_a

  # if count is > 0 we are going to put it to use.
  # otherwise set it to 0
  count = count > 0 ? count : 0

  if count > 0
    from = hist.length - count
    history_array = history_array[from..-1] 

  printing history_array.join("n")

Save the file and begin a IRB that is new session. Then kind history 2 and you should see just the final two ines of the history.

you use frequently, remember that each library you load increases the load time of the IRB session, which can make it less pleasant to use while you can use .irbrc to load libraries. You're often better off loading libaries that are specific with require statements.


IRB provides a location to try out Ruby rule. It is a way that is great work-out system logic before placing it in a file.

Now you are confident with IRB, you can make use of it to explore Ruby's different information kinds by after these tutorials and IRB that is using to the examples.

Install WordPress on Nginx Ubuntu VPS via EasyEngine

Previous article

Installing Lemur Certificate Manager on Ubuntu

Next article

You may also like


Leave a reply

Your email address will not be published. Required fields are marked *