We all know the feeling: before starting a new script you hack around in IRB to try out some things, but once you’re done you realize that now you either have to type everything again or copy/paste from the IRB session (or the history file if you keep one). So I set out on my search for a solution and found an old ruby-talk post by Gavin Sinclair , which implemented a method called dumphist , which I modified to my needs and put in my ~/.irbrc:
Let’s look at the following IRB session:
1
2
3
4
5
6
7
8
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12
<span class='line'><span class="o">>></span> <span class="nb">puts</span> <span class="s2">"hello"</span>
</span><span class='line'><span class="n">hello</span>
</span><span class='line'><span class="o">=></span> <span class="kp">nil</span>
</span><span class='line'><span class="o">>></span> <span class="nb">puts</span> <span class="s2">"world"</span>
</span><span class='line'><span class="n">world</span>
</span><span class='line'><span class="o">=></span> <span class="kp">nil</span>
</span><span class='line'><span class="o">>></span> <span class="k">def</span> <span class="nf">foo</span>
</span><span class='line'><span class="o">.</span><span class="n">.</span> <span class="nb">puts</span> <span class="s1">'bar'</span>
</span><span class='line'><span class="o">.</span><span class="n">.</span> <span class="k">end</span>
</span><span class='line'><span class="o">=></span> <span class="kp">nil</span>
</span><span class='line'><span class="o">>></span> <span class="n">dumphist</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="s1">'test.rb'</span><span class="p">)</span>
</span><span class='line'><span class="o">=></span> <span class="o">[</span><span class="s2">"def foo"</span><span class="p">,</span> <span class="s2">"puts 'bar'"</span><span class="p">,</span> <span class="s2">"end"</span><span class="o">]</span>
</span>
The last command created a file named test.rb for us, which contains only the method foo. :-)