citizen428.blog()

Try to learn something about everything

Create Script From IRB Session

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">&gt;&gt;</span> <span class="nb">puts</span> <span class="s2">&quot;hello&quot;</span>
</span><span class='line'><span class="n">hello</span>
</span><span class='line'><span class="o">=&gt;</span> <span class="kp">nil</span>
</span><span class='line'><span class="o">&gt;&gt;</span> <span class="nb">puts</span> <span class="s2">&quot;world&quot;</span>
</span><span class='line'><span class="n">world</span>
</span><span class='line'><span class="o">=&gt;</span> <span class="kp">nil</span>
</span><span class='line'><span class="o">&gt;&gt;</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">&#39;bar&#39;</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">=&gt;</span> <span class="kp">nil</span>
</span><span class='line'><span class="o">&gt;&gt;</span> <span class="n">dumphist</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;test.rb&#39;</span><span class="p">)</span>
</span><span class='line'><span class="o">=&gt;</span> <span class="o">[</span><span class="s2">&quot;def foo&quot;</span><span class="p">,</span> <span class="s2">&quot;puts &#39;bar&#39;&quot;</span><span class="p">,</span> <span class="s2">&quot;end&quot;</span><span class="o">]</span>
</span>

The last command created a file named test.rb for us, which contains only the method foo. :-)

Comments

Copyright © 2016 - Michael Kohl - Powered by Octopress