IRB (Interactive Ruby)

repository·master·Indexed 19 days ago

https://github.com/ruby/irb

A REPL (Read-Eval-Print Loop) tool for executing Ruby expressions interactively, prototyping code, and debugging applications. It is a default gem in Ruby and provides features such as binding.irb breakpoints, custom command and helper method extensions, and integration with debug.gem for full debugger sessions. Includes documentation on configuration via .irbrc files, command-line options, and a feature comparison with Pry.

Tokens
15.5K
Snippets
60
Records
84
Agent score
66%

What's inside irb

  1. How to choose between Commands and Helper Methods in IRB

    master

    When extending IRB, you must decide whether to implement a Command or a Helper Method.

    Use a Command if:

    • The operation is a utility performing non-Ruby related tasks (e.g., edit).
    • The operation displays information (e.g., show_source).
    • The operation requires non-Ruby syntax arguments (e.g., ls -g pattern or flags like --flag).
    • Commands are generally safer as they can handle a wider variety of inputs that might not be valid Ruby code.

    Use a Helper Method if:

    • The operation is meant to return a Ruby object that interacts with the application.
    • You want the user to be able to chain methods (e.g., my_helper(arg).foo).
    • You are providing shortcuts for frequently used Ruby operations or data structures.
  2. Understand IRB configuration precedence

    master

    IRB configurations are applied from multiple sources. When multiple sources define the same setting, the following precedence order applies (from highest to lowest priority):

    1. Command-Line Options: Overrides default settings when starting IRB.
    2. Configuration File: Ruby code in an .irbrc file.
    3. Environment Variables: Variables like IRB_USE_AUTOCOMPLETE.
    4. Hash IRB.conf: The current configuration settings in the session.

    Important Notes:

    • If a conflict exists between an entry in the IRB.conf hash and a command-line option, the hash entry wins.
    • Changes made to IRB.conf during a session generally do not affect the context once the session has started; they are primarily effective during the initial configuration file interpretation.
  3. Use Evaluation History and Shortcuts

    master

    By default, IRB does not save evaluation history. You can enable it to access previous results using special variables.

    Enabling History

    • Configuration file: IRB.conf[:EVAL_HISTORY] = n (where n is the max number of evaluations; 0 stores all history).
    • Session method: conf.eval_history = n.

    Accessing History

    Once enabled, you can use the following:

    • _: Contains the most recent evaluation (same as conf.last_value).
    • __: Contains the entire evaluation history.
    • __[m]: Accesses a specific evaluation from history:
      • Positive m: The m-th evaluation in history.
      • Negative m: The m-th evaluation from the end.
      • 0: Returns nil.
    irb(main):001> conf.eval_history = 5
    => 5
    irb(main):002> :foo
    => :foo
    irb(main):003> :bar
    => :bar
    irb(main):004> _
    => :bar
    irb(main):005> __[1]
    => :foo
  4. Enable Type-Based Completion with IRB::TypeCompletor

    master

    IRB offers an experimental IRB::TypeCompletor that uses type analysis to provide more intelligent autocompletion (e.g., autocompleting chained methods, block parameters, and array methods) compared to the default RegexpCompletor.

    1. Install the dependency

    $ gem install repl_type_completor

    Or add to your Gemfile:

    gem 'irb'
    gem 'repl_type_completor', group: [:development, :test]

    2. Enable it

    You can enable it using one of three methods:

    Option A: Command Line Flag

    $ irb --type-completor

    Option B: Configuration File (e.g., ~/.irbrc)

    IRB.conf[:COMPLETOR] = :type

    Option C: Environment Variable

    $ export IRB_COMPLETOR='type'
    irb

    3. Verify Installation

    Inside IRB, run irb_info and check the Completion section. It should show ReplTypeCompletor instead of RegexpCompletor.

  5. Install IRB

    master

    IRB is a default gem in Ruby and typically does not require separate installation. If you are using Ruby 2.6 or later and need to install or upgrade a specific version, you can use gem install or bundler.

    $ gem install irb
  6. Use the `irb` executable for interactive sessions

    master

    You can start a fresh interactive Ruby session by typing irb in your terminal. In this session, you can evaluate Ruby expressions or prototype scripts. An input is executed once it is syntactically complete.

    $ irb
    irb(main):001> 1 + 2
    => 3
    irb(main):002* class Foo
    irb(main):003*   def foo
    irb(main):004*     puts 1
    irb(main):005*   end
    irb(main):006> end
    => :foo
    irb(main):007> Foo.new.foo
    1
    => nil
  7. Locate and use IRB configuration files

    master

    IRB searches for a configuration file (containing Ruby code) in the following order:

    1. $IRBRC
    2. $XDG_CONFIG_HOME/irb/irbrc
    3. $HOME/.irbrc
    4. $HOME/.config/irb/irbrc (only if XDG_CONFIG_HOME is not set)
    5. .irbrc in the current directory
    6. _irbrc in the current directory
    7. $irbrc in the current directory

    To prevent any configuration file from being loaded, use the -f command-line option.

    You can check if a configuration file was successfully read using conf.rc? or by checking the IRB.conf[:RC] hash entry.

    irb(main):001> conf.rc?
    => true
  8. Load modules at IRB startup

    master

    You can specify modules to be required automatically when IRB starts. This is only effective during session startup. The configuration file entry overrides command-line options.

    Methods to set modules:

    1. Command-line: Use the -r flag multiple times.
    2. Configuration File: Set the IRB.conf[:LOAD_MODULES] hash entry.
    $ irb -r csv -r json
    IRB.conf[:LOAD_MODULES] = %w[csv json]
    # Using command line
    $ irb -r csv -r json
    
    # Using configuration file
    IRB.conf[:LOAD_MODULES] = %w[csv json]
  9. Debug with IRB and debug.gem

    master

    Starting from version 1.8.0, IRB integrates with debug.gem. When you hit a binding.irb breakpoint, you can transition from the IRB REPL to a full debugger session.

    Activating the Debugger

    When execution pauses at a binding.irb line:

    1. Type debug to activate the debugger.
    2. If debug is already in scope, you can call irb_debug.

    Once activated, the prompt changes to irb:rdbg. You can then use all debug.gem commands (like next, step, info, continue) while still retaining access to IRB commands like show_source and show_doc.

    Limitations

    • binding.irb does not support pre and do arguments (use binding.break for those).
    • Remote debugging via debug.gem is not supported in IRB.
    • The underscore _ (previous return value) is not supported inside the irb:rdbg session.
    # In your Ruby code
    def my_method
      binding.irb
      puts "Done"
    end
    
    my_method
    # Inside the IRB session at the breakpoint
    irb(main):001> debug
    irb:rdbg(main):002> next
  10. Specify extra RI documentation directories

    master

    You can add additional paths to RI documentation directories to be loaded at startup. This is only effective during session startup. The configuration file entry overrides command-line options.

    Methods to set directories:

    1. Command-line: Use the --extra-doc-dir flag.
    2. Configuration File: Set the IRB.conf[:EXTRA_DOC_DIRS] hash entry.
    $ irb --extra-doc-dir your_doc_dir --extra-doc-dir my_doc_dir
    IRB.conf[:EXTRA_DOC_DIRS] = %w[your_doc_dir my_doc_dir]
    # Using command line
    $ irb --extra-doc-dir your_doc_dir --extra-doc-dir my_doc_dir
    
    # Using configuration file
    IRB.conf[:EXTRA_DOC_DIRS] = %w[your_doc_dir my_doc_dir]
  11. Start an IRB session

    master

    To start a fresh interactive session, run irb from your terminal. You can evaluate Ruby expressions or prototype scripts. Input is executed once it is syntactically complete.

    $ irb
    irb(main):001> 1 + 2
    => 3
  12. Configure End-of-File (Ctrl-D) and SIGINT (Ctrl-C) behavior

    master

    You can control how IRB responds to interrupt signals via configuration:

    End-of-File (Ctrl-D)

    By default, Ctrl-D exits the session. To prevent this, set: IRB.conf[:IGNORE_EOF] = true

    In-session methods: conf.ignore_eof? (returns boolean) and conf.ignore_eof = boolean.

    SIGINT (Ctrl-C)

    By default, Ctrl-C does not exit the session. To make it exit the session, set: IRB.conf[:IGNORE_SIGINT] = false

    In-session methods: conf.ignore_sigint? (returns boolean) and conf.ignore_sigint = boolean.