Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I defined a Ruby method in IRB, how do I edit that method without retyping everything?

Tags:

ruby

irb

Say I am running IRB and I type this into the console:

def full_name(first, last)
   puts "Your full name is: #{first, ' ', last}"
end

Say, that I wanted to edit that to include the parameter middle, how would I just bring back up that same method and edit the parameter list and edit the puts statement without having to retype the entire method?

P.S. I know that this example is simple and I could easily just retype the method, but I have much larger methods I am experimenting with and I am using this simple one for brevity.

Thanks.

like image 870
marcamillion Avatar asked Mar 12 '12 22:03

marcamillion


People also ask

Can you explain how Ruby looks up a method to invoke?

Method names in Ruby should begin with a lowercase letter. If you begin a method name with an uppercase letter, Ruby might think that it is a constant and hence can parse the call incorrectly. Methods should be defined before calling them, otherwise Ruby will raise an exception for invoking an undefined method.

How do you add to a method in Ruby?

Ruby | Set add() method The add is an inbuilt method in Ruby which adds an element to the set. It returns itself after addition. Parameters: The function takes the object to be added to the set. Return Value: It adds the object to the set and returns self.

How do you use IRB in Ruby?

To use it, you launch the irb executable and type your Ruby code at the prompt. IRB evaluates the code you type and displays the results. IRB gives you access to all of Ruby's built-in features, as well as any libraries or gems you've installed.

What does it mean when a method ends with in Ruby?

indicates that the method is a potentially dangerous version of another method. Many times, ! does modify the receiver (and that is what is dangerous), but other times other effects occur. For example, in Rails, the ActiveRecord save and save!


1 Answers

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).

like image 78
Andrew Marshall Avatar answered Sep 18 '22 07:09

Andrew Marshall