Monday, June 18, 2007

.irbrc Modifications

Last October, Ben Bleything added a Unix-style history method to his irb (and by extension to script/console).

I did this myself in February or March, but Ben's solution is better than mine. Mine used an explicit eval() and could result in eval() loops for that reason. Ben's avoids that problem nicely. It also adds nifty features like writing your history to a file, calling prior commands by number - so you can call any command in your history, not just the most recent - and calling several commands in one call.

However, there's one part I don't dig: Ben's version returns nil. So if you use h! to get the return value you got before, you get nil instead. It means that the simplest use case for history, just calling the same command twice, is only useful if you didn't care about the return value. Personally, I usually only capture the return value in a variable after I see it in irb's output - using the _ special variable - so for me return values are very useful.

Changing that turns out to be very easy. Ben's history_do method explicitly returns nil, and his irb_eval doesn't capture its internal eval()'s return value. So the changes are very slight, and very quick to make. Capture the return value, and take out the nil. Easy.

Here's the diff.

Here's my version.

3 comments:

  1. Is it just me, or does this have a bug in it?
    When trying to run it as is, I'm getting:
    >> history
    TypeError: String can't be coerced into Fixnum


    The problem looks to be in the print_line method:
    print line_number + ": " if show_line_numbers

    I changed this to:
    print line_number.to_s + ": " if show_line_numbers


    And everything looks peachy now.
    Quite handy, thanks Giles!

    ReplyDelete
  2. Doh! That's one of the changes I added. (Weirdly, I never saw that bug.)

    ReplyDelete

Note: Only a member of this blog may post a comment.