Sunday, September 24, 2006

Enhance your irb experience on Windows

You can extend the functionality of your irb on Windows by creating a file .irbrc in your %userprofile% directory. Put some Ruby code in there, and they will get loaded when you launch your irb, as well as your script/console. I have put in some code snippets in there to aid my irb experience.

(You may have issues trying to create a file with its name beginning with a period on Windows Explorer. Try to run the command "notepad .irbrc" in your cmd.exe)

Tab Completion

require 'irb/completion'
ARGV.concat [ "--readline", "--prompt-mode", "simple" ]
Do you miss intellisense? If you do this, then in irb, type in like "text".s[tab][tab] will give you a list of methods in String that starts with s.

Ruby Interactive (ri) reference in irb
def ri(*names)
system(%{echo | ri #{names.collect { |name| name.to_s }.join(" ")}})
end
Then you can type ri 'String.strip' to see the Ruby index. The argument has to be a string though.

Remember, on a Windows machine, you have to put "echo | " in front of your ri line or else your irb will just return 'false'. I know it's counterintuitive that it isn't at the end, but it works.

Clear screen
def cls
system('cls')
end
I always wanted clear screen...

Console messed up with long irb lines
If you have a line of Ruby code that is way too long, and you want to go back and make changes, on Windows console it is not very friendly as it will almost guarentee to mess up your edits and disorient your typings. The only way I Googled on how to fix this is to take away the "--readline" switch from the Tab Completion tip above, and replace it with "--noreadline". But then you lose Tab Completion of course. I haven't found a workaround for it yet, but in the mean time I will happily just use Cygwin bash shell =)

4 comments:

Anonymous said...

The Tab-completion thing is great.

The ri trick doesn't work for me, though:

irb(main):001:0> ri "String.strip"
NoMethodError: undefined method `ri' for main:Object
from (irb):1
from :0

Stephen Chu said...

I'm not sure. The code above works for me. I remember I had to either reboot or do something else to force the new code in .irbrc to kick in my irb session.

adam said...

change this line
system(%{echo | ri #{names.collect { |name| name.to_s }.join(" ")}})

to

system(%{echo | ri.bat #{names.collect { |name| name.to_s }.join(" ")}})

to get tab completion to work

Jessica said...

anonymous: I had the same problem with ri not working. I found the answer here: http://rubyforge.org/pipermail/poignant-stiffs/2004-July/000094.html

Basically, run ri directly from the command prompt, not from within irb.