If I defined a Ruby method in IRB, how do I edit that method without retyping everything?
You can't. Other than retyping/repasting it, or pressing ↑ to get all the previous statements, but for longer methods this can be very confusing.
Why not type your code in an editor, and then do load 'mycode.rb'
in IRb? This is essentially equivalent to copy-and-pasting the text in, and calling load 'myfile.rb'
again will, as usual, override the existing method definitions.
Or, even better, use Pry instead of IRB as suggested by bannister below (I completely replaced IRB with Pry long ago myself).
You can do this easily in Pry (a much more powerful alternative to IRB), simply use the edit-method
command to reopen the method in an editor as follows:
[19] (pry) main: 0> def full_name(first, last)
[19] (pry) main: 0* puts "Your full name is: #{first + '' + last}"
[19] (pry) main: 0* end
=> nil
[20] (pry) main: 0> edit full_name
Waiting for Emacs...
=> nil
[21] (pry) main: 0> show-method full_name
From: (pry) @ line 32:
Number of lines: 3
Owner: Object
Visibility: public
def full_name(first, middle, last)
puts "Your full name is: #{first + middle + last}"
end
[22] (pry) main: 0> full_name "Stephen ", "william ", "Hawking"
Your full name is: Stephen william Hawking
=> nil
[23] (pry) main: 0>
Pry automatically reloads the method after editing is complete (the editor pry uses can also be configured)
I don't think you have a lot of options here. What I usually do is to place the code I'm playing with in a file and use load '/path/to/file.rb'
to reload it whenever I change something.
You can also try the interactive_editor
gem which allows you to use a full-blown text editor for text editing inside an IRB session.