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.
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.
I really like Wirble, it adds color coding and persistent history and even tab completion.
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>
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
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 }
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)
IRB subsessions let you try things without ending or affecting any of your existing subsessions. The commands to work with subsessions are:
>> 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"
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.
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.
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
~ $
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).
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.
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.
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 --
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.
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
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
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>
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
>>
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
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/
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")