Page Content

Tutorials

IRB In Ruby: Instant Coding With The Interactive Shell

IRB in Ruby

The standard Ruby distribution includes the invaluable Interactive Ruby Shell (IRB), which offers a shell for instant experimentation and debugging. It is basically a Read-Eval-Print Loop (REPL) that removes the need for programmers to repeatedly create and run small program files by enabling them to type Ruby expressions and view the results instantly.

Key Features and Basic Usage

Starting and Exiting IRB

To initiate an IRB session, just type irb into the command prompt.

The context (such as irb(main)) and the line number are included in the longer prompt that appears when you run irb without any special options.

Example of starting IRB (default prompt):

$ irb
irb(main):001:0> 

As an alternative, a cleaner prompt can be shown by using the --simple-prompt option:

$ irb --simple-prompt
>> 2+2
=> 4
>> exit
$ 

By typing exit, quit, irb_exit, or irb_quit, or by entering an end-of-file character (such as Ctrl+D on Unix systems), you can end an IRB session.

You can also read What Is Mean by Method Resolution In Ruby With Code Example

Understanding IRB Output

Output is only generated in a standard Ruby program file when an explicit output method, such as puts, is called. IRB, however, outputs the return value of each expression you type.

In ASCII, the => arrow indicates the return value.

Code Example Demonstrating Output: | Expression Entered in IRB | Description | Output/Result Shown | Source | | :— | :— | :— | :— | | 2**3 | Exponentiation | => 8 | | | "Ruby! " * 3 | String repetition | => "Ruby! Ruby! Ruby! " | | | x = 3 | Assignment (returns the value assigned) | => 3 | | | puts "Hello" | Prints the string, then returns the method’s value | Hello then => nil | |

Interactive Method Definition

Complex code structures, such as methods, can be defined right within the interactive session.

Code Example of Defining a Method in IRB:

irb(main):001:0> def sum(n1, n2)
irb(main):002:1> n1 + n2
irb(main):003:1> end
=> nil
irb(main):004:0> sum(3, 4)
=> 7

Output

7

When a method is defined, the def…end structure’s initial return value is nil. Until the statement is finished, the prompt finishes with an asterisk * if a phrase takes up more than one line.

You can also read Exception In Ruby: Custom Classes And The Hierarchy

Advanced IRB Features

Debugging with Embedded Sessions

For debugging, IRB is quite helpful, especially when used with the binding.either the irb feature (available since Ruby 2.4.0) or third-party tools such as pry-byebug.

By adding two lines, you may launch an interactive IRB session from within any running Ruby script:

require 'irb'
binding.irb

An IRB REPL begins and the program pauses when the script execution reaches binding.irb. All of the local and instance variables that are currently in scope are accessible to you within this session, together with the expected value for yourself. You can either exit or use Ctrl+D to restart the software.

Tab Completion ()

Tab completion is available in IRB if your Ruby installation supports Readline. As you type, this tool offers method suggestions.

Example of using Tab Completion:

  • Start an IRB session with the completion library enabled: % irb -r irb/completion (or require 'irb/completion' inside IRB)
  • Define a string object: irb(main):002:0> a = "cat"
  • Type a.re and press TAB twice; IRB suggests relevant methods: a.reject a.replace a.respond_to? a.reverse a.reverse!

In your.irbrc configuration file, you might include require ‘irb/completion‘ if you commonly utilize this feature.

You can also read What Is Code Blocks In Ruby With Practical Code Examples

Subsessions and Context Management

IRB allows for subsessions, which are several concurrent sessions.

  • You can create a subsession by typing irb inside an existing session.
  • Every active session is listed with the jobs command.
  • To switch to a designated subsession n, use the fg n command.

The value of self (the implicit receiver) in the new binding is the object you specify when creating a subsession. The methods of an object can be easily experimented with in this way.

Code Example of Using an Object as Subsession Context: If you have an object v of class VolumeKnob:

irb(main):008:0> irb v
irb#3(#<VolumeKnob:0x401e7d40>):001:0> up
=> 60
# In this subsession, 'up' is implicitly called on the object v

It is possible to modify a subsession’s binding (scope) manually with cb or implicitly with irb .

Configuration ()

IRB searches for an initialization file upon startup, such as ~/.irbrc. You can alter the environment with this file’s arbitrary Ruby code and configuration variables.

You can enhance IRB, for instance, by adding new top-level methods to the initialization file. For instance, you could make a function called ri that invokes the external Ruby Interactive documentation tool:

def ri(*names)
  system(%{ri #{names.map {|name| name.to_s}.join(" ")}})
end

Altering the IRB.conf hash allows you to adjust configuration values as well (e.g., setting prompt styles or backtrace limitations).

IRB in Context

An essential tool for working with the Ruby API, IRB is a fundamental component of learning and experimenting with the language. It performs well with brief and simple commands. There are a lot of code examples in Ruby documentation that may be typed into an IRB session for practice.

You can also read Ruby Enumerable Module: Essential Methods Every Developer

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index