tags:

views:

5153

answers:

23

What's your favourite IRB tip or trick? It could be a handy shortcut within the IRB console itself or maybe a .irbrc customization.

I really like that you can type an underscore to retrieve the result of the last expression.

+26  A: 

I really like Wirble, it adds color coding and persistent history and even tab completion.

Frew
.... dow. you beat me to it.
Kent Fredric
+3  A: 

I install wirble

Enables Colourisation and gets the readline support for completion/scrollback going without having to remember a bunch of incantations

$cat ~/.irbrc 
require "rubygems"
require "wirble"
Wirble.init
Wirble.colorize

$irb
>> [1,2,3]
=> [1, 2, 3]
>> [1,2,3].<TAB>
Display all 118 possibilities? (y or n)

[1,2,3].empty?                           [1,2,3].inspect                        
[1,2,3].po                               [1,2,3].send
[1,2,3].__id__                           [1,2,3].entries                          
[1,2,3].instance_eval                    [1,2,3].poc

<snip>

Kent Fredric
+2  A: 

A while ago, I messed around with jruby and rubinius regularly. Since I had a slightly pimped up irbrc, I always had problems with dependencies, like gems who didn't work or weren't installed on a given runtime.

So I concocted a more forgiving require. It accepts a block, which is executed if a library is successfully loaded. Otherwise a simple error message is printed.

def try_require(what, &block)
  loaded, require_result = false, nil

  begin
    require_result = require what
    loaded = true

  rescue Exception => ex
    puts "** Unable to require '#{what}'"
    puts "--> #{ex.class}: #{ex.message}"
  end

  yield if loaded and block_given?

  require_result
end

This then lets me require straightforward stuff:

try_require 'pp'

Or stuff requiring configuration

try_require('wirble') do
  Wirble.init(:skip_prompt=>true)
  Wirble.colorize
end
webmat
+13  A: 

I like to have a quick way to benchmark a piece of code. This was inspired by one of the Rubinius devs:

# Quick benchmarking
# Based on rue's irbrc => http://pastie.org/179534
def quick(repetitions=100, &block)
  require 'benchmark'

  Benchmark.bmbm do |b|
    b.report {repetitions.times &block} 
  end
  nil
end

Can be used like this for the default 100 executions:

quick { rand }

Or like this for more:

quick(10000) { rand }
webmat
+6  A: 

The simplest of my tips is simply to always have a hash and an array pre-defined. That way I don't have to whip up something when I'm messing around trying out Enumerable, Array or Hash methods.

HASH = { 
  :bob => 'Marley', :mom => 'Barley', 
  :gods => 'Harley', :chris => 'Farley'} unless defined?(HASH)
ARRAY = HASH.keys unless defined?(ARRAY)
webmat
+31  A: 

IRB subsessions let you try things without ending or affecting any of your existing subsessions. The commands to work with subsessions are:

  • irb start a new subsession
  • jobs list subsessions
  • fg # switch to a subsession
  • kill # kill a subsession
>> my_string = "foo"
=> "foo"
>> irb
>> my_string
NameError: undefined local variable or method `my_string' for main:Object
    from (irb#1):1
>> jobs
=> #0->irb on main (#: stop)
#1->irb#1 on main (#: running)
>> fg 0
=> #, @signal_status=:IN_EVAL, @scanner=#>
>> my_string
=> "foo"
Jeff Dallien
Accepted because this is my favourite of the tips given!
John Topley
In Ruby 1.9.1 the behavior has changed a bit. It looks like you are now required to specify a name for the session, i.e `irb 'temp'`. Other than that everything seems to behave the same, though there may be other new features I'm unaware of.
Peter Wagenet
+5  A: 

I like utility belt. Particularly the editor integration is nice as is the ability to google straight from irb. Also it includes Wirble and has some nice tricks for Mac OS X clipboard interaction.

robertpostill
+9  A: 

Returning nil after a command like this. Example from Rails:

people = Person.all
#=> screenfuls of people and their attributes as the command returns an array of people

Avoid screenfuls like this:

people = Person.all; nil #=> nil

Simple.

Dave Nolan
I sometimes to this too. However, I think there's an option to turn it off if it's a big enough nuisance.
Andrew Grimm
I prefer to use people.size after, so I get some useful data :)
Fabiano PS
+2  A: 

I have customized the color scheme for wirble behind a white-background terminal.

# load libraries
require 'rubygems'
require 'wirble'

colors = Wirble::Colorize.colors.merge({
  :object_class => :black,
  :class        => :dark_gray,
  :symbol       => :red,
  :symbol_prefix=> :blue,
})

# start wirble (with color)
# set the colors used by Wirble
Wirble::Colorize.colors = colors

Wirble.init

Wirble.colorize
~ $
Binarycrayon
+1  A: 

I have these to help keep output manageable:

  class Array
    alias :__orig_inspect :inspect
    def inspect
      (length > 20) ? "[ ... #{length} elements ... ]" : __orig_inspect
    end
  end

  class Hash
    alias :__orig_inspect :inspect
    def inspect
      (length > 20) ? "{ ... #{length} keys ... }" : __orig_inspect
    end
  end

Instead of a screen full of results it returns [ ... 22 elements ... ] if there are more than 20 elements returned. Got it off a website so attribution to them (I've forgotten the specific site).

inkdeep
+6  A: 

I wrote up a comprehensive tutorial on irb commands like fg and jobs.

+27  A: 

The ability to assign from the last expression after the fact:

>> 1 + 2 + 3
=> 6
>> x = _
=> 6
>> x
=> 6
>>

Saves a lot of typing when you forget that you really wanted to assign that last expresion to a variable.

runako
this one is a huge timesaver :)
Darth
+4  A: 

I like starting irb as a poor-mans debugger when the objects I would like to inspect are too complicated to print.

... your script here ...
$myvar = myvar
require 'irb'; require 'irb/completion'
IRB.start

On a side-note, I tend to just use irb/completion, which is bundled with ruby instead of wirble.

zimbatm
+3  A: 

I love this one. You can fetch documentation inline by prepending ri_ to any method.

It gives you inline documentation like this:

irb(main):002:0> ['a','b'].ri_each
------------------------------------------------------------- Array#each
     array.each {|item| block }   ->   array
------------------------------------------------------------------------
     Calls block once for each element in self, passing that element as 
     a parameter.

        a = [ "a", "b", "c" ]
        a.each {|x| print x, " -- " }

     produces:

        a -- b -- c --
Joe W.
Samuel Danielson
+30  A: 

Funny coming back to an old question I contributed to :-)

Here's another tool I added to my IRB config. Very practical for exploring unfamiliar classes and apis:

class Object
  # Return only the methods not present on basic objects
  def interesting_methods
    (self.methods - Object.new.methods).sort
  end
end

This lets me see only non trivial methods in a sane order on any class or instance I'm exploring.

webmat
Ooh, I like that!
John Topley
Seconded - this is a really need trick!
Chris Adams
You should use `Object.instance_methods` instead of `Object.new.methods`. Also, you can just replace that whole thing with `self.methods false`
Adrian
Good observation about using instance_methods. As for self.methods false, no, it doesn't do the same.
webmat
This is awesome! Glad to have re-found this.
Bijan
+1  A: 

Different twist on Wirble color customization:

require 'wirble'
# blue is hard to see on black, so replace all blues with purple
Wirble::Colorize::Color::COLORS.merge!({
  :blue => '0;35'
})
Wirble.init
Wirble.colorize
Khaled Agrama
+4  A: 

I use this trick sometimes when reading other peoples code, You can find out who defines a method using this approach:

object.method(:method_name)

p 2.method(:odd?)
<Method: Fixnum#odd?>
p User.method(:acts_as_commentable)
<Method: Class(Juixe::Acts::Commentable::ClassMethods)#acts_as_commentable>

These are some simple examples, it can be really handy when you are tracking down functionality in a plugin or gem.

I found this originally here

paulthenerd
+3  A: 

Irb subsessions can take an object; that object will be "self" in the subsession

irb(main):003:0> irb [1, 2, 3]
irb#1(123):001:0> size
=> 3
irb#1(123):002:0> each { |i| puts i }
1
2
3
=> [1, 2, 3]
irb#1(123):003:0>
Wayne Conrad
+3  A: 

This is inspired by webmat's "interesting_methods" answer:

def colputs(array)
  def num_columns; 4; end
  def col_width; 25; end
  def force_length(x)
    x = x.to_s
    max_length = col_width+2
    if x.length > max_length
      x = x[0..max_length-4] + '...'
    end
    x += (' '*max_length)
    x[0..max_length-1]
  end
  def get_element(array, i) # displays in column order instead of row order
    num_rows = (array.length/num_columns)+1
    col = i % num_columns
    row = i / num_columns
    array[col*num_rows+row]
  end
  for i in (0..array.length)
    print force_length(get_element(array, i))
    print "  "
    puts if (i % num_columns) == (num_columns-1)
  end
  nil
end

class Object
  # Return only the methods not present on basic objects
  def show_methods
    colputs (self.methods - Object.new.methods).sort
  end
end

This gives you a colputs method that lets you print out long arrays in columns. show_methods uses colputs. Here's an example:

>> [1,2,3].show_methods
&                            delete_if                    insert                       reverse_each                 
*                            detect                       join                         rindex                       
+                            each                         last                         select                       
-                            each_index                   length                       shift                        
<<                           each_with_index              map                          size                         
<=>                          empty?                       map!                         slice                        
[]                           entries                      max                          slice!                       
[]=                          fetch                        member?                      sort                         
all?                         fill                         min                          sort!                        
any?                         find                         nitems                       sort_by                      
assoc                        find_all                     pack                         to_ary                       
at                           first                        partition                    transpose                    
clear                        flatten                      pop                          uniq                         
collect                      flatten!                     push                         uniq!                        
collect!                     grep                         rassoc                       unshift                      
compact                      include?                     reject                       values_at                    
compact!                     index                        reject!                      yaml_initialize              
concat                       indexes                      replace                      zip                          
delete                       indices                      reverse                      |                            
delete_at                    inject                       reverse!                                                  
=> nil
>> 
techiferous
+5  A: 

Awesome Print


require "rubygems"
require "ap"

IRB::Irb.class_eval do
  def output_value
    ap @context.last_value, 
            :multiline => false,
            :plain  => false,
            :indent => 2,
            :color => {
                :array      => :white,
                :bignum     => :blue,
                :class      => :yellow,
                :date       => :greenish,
                :falseclass => :red,
                :fixnum     => :blue,
                :float      => :blue,
                :hash       => :gray,
                :nilclass   => :red,
                :string     => :yellowish,
                :symbol     => :cyanish,
                :time       => :greenish,
                :trueclass  => :green
            }
  end 
end

alt text

Chirantan
NOOBnote: You'll need to install the awesome_print gem for this to work. `gem install awesome_print`
inkdeep
awesome :) Using it right away.
Vijay Dev
+1  A: 

I like: irb_rocket

Ragmaanir
A: 

Easily fetch the results of a call to a path on your app:

http://snipplr.com/view/37506/fetch-a-page-from-your-site-from-console/

insane.dreamer
A: 

I use stuff brought in by irb_hacks gem.

Snippets, save a lot of keystrokes when working on a specific feature:

irb> ae
(snippet)>> puts ["Hello, world"] + args
irb> a
Hello, world
irb> a "and me"
Hello, world
and me

Interactively browsing program data with GNU less:

less Dir["/etc/**/*"]
less File.read("/etc/passwd")
dadooda