<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Seven steps &#187; ruby</title>
	<atom:link href="http://trevoke.net/blog/category/technology/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://trevoke.net/blog</link>
	<description>Martial arts and technology, $DEITY what a mix!</description>
	<lastBuildDate>Wed, 01 Feb 2012 03:43:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Ruby: What is at_exit and how to write tests for it.</title>
		<link>http://trevoke.net/blog/2012/01/06/ruby-what-is-at_exit-and-how-to-write-tests-for-it/</link>
		<comments>http://trevoke.net/blog/2012/01/06/ruby-what-is-at_exit-and-how-to-write-tests-for-it/#comments</comments>
		<pubDate>Fri, 06 Jan 2012 16:35:03 +0000</pubDate>
		<dc:creator>Trevoke</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[at_exit]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://trevoke.net/blog/?p=319</guid>
		<description><![CDATA[Ruby has a neat feature called at_exit which takes a block and then executes the contents of this block when the program ends. There are a couple of VERY important details: It takes a block and converts it into a Proc object at the time of parsing. This means that the data has to be <a href='http://trevoke.net/blog/2012/01/06/ruby-what-is-at_exit-and-how-to-write-tests-for-it/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Ruby has a neat feature called at_exit which takes a block and then executes the contents of this block when the program ends. There are a couple of VERY important details:</p>
<ol>
<li>It takes a block and converts it into a Proc object at the time of parsing. This means that the data has to be available in the binding, or you&#8217;ll run into errors. Example: instance variables need to be set before you can use them in that block. Better idea: don&#8217;t use instance variables in there at all.</li>
<li>You can &#8216;chain&#8217; at_exit calls, and they will be resolved in a First In, Last Out (FILO) order.</li>
</ol>
<p>Once you know this, using at_exit and writing tests for it becomes a little easier:</p>
<pre class="brush: ruby; title: ; notranslate">class Piddler
   def initialize
     create_pid_file
   end

   private

   def create_pid_file
     pid_file = &quot;/tmp/piddler/my_pid&quot; #Simplified for example purposes
     File.new(pid_file, 'w')
     at_exit { FileUtils.rm_f pid_file }
   end
end</pre>
<p>What you&#8217;ll notice is that the at_exit block is defined RIGHT AFTER I create what I will need to resolve/undo/finish &#8211; not separately, right inside the method.</p>
<p>&nbsp;</p>
<pre class="brush: ruby; title: ; notranslate">def test_clears_pid_file_when_it_exits
   at_exit { assert_equal 0, Dir['/tmp/piddler/*].size}
   Piddler.new
end
</pre>
<p>The advantage of that is that I know exactly when it gets defined. For this example, it gets defined at the end of the &#8216;initialize &gt; create_pid_file&#8217; call. This means that any at_exit blocks defined BEFORE that will be resolved AFTER.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://trevoke.net/blog/2012/01/06/ruby-what-is-at_exit-and-how-to-write-tests-for-it/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby callbacks (hooks)</title>
		<link>http://trevoke.net/blog/2010/03/31/ruby-callbacks-hooks/</link>
		<comments>http://trevoke.net/blog/2010/03/31/ruby-callbacks-hooks/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 17:28:13 +0000</pubDate>
		<dc:creator>Trevoke</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://trevoke.net/blog/?p=177</guid>
		<description><![CDATA[Hooks are a fascinating bit of Ruby magic. They are methods you can define with actions to run when something happens. You can put triggers in your code. This blog post explains them very well; and for more information, get &#8220;Metaprogramming Ruby&#8221;, which is a great book &#8211; not only about the callbacks, but about <a href='http://trevoke.net/blog/2010/03/31/ruby-callbacks-hooks/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Hooks are a fascinating bit of Ruby magic. They are methods you can define with actions to run when something happens. You can put triggers in your code.</p>
<p>
<a  href="http://www.khelll.com/blog/ruby/ruby-callbacks/" onclick="javascript:pageTracker._trackPageview('/external/www.khelll.com/blog/ruby/ruby-callbacks/');" >This blog post</a> explains them very well; and for more information, get &#8220;Metaprogramming Ruby&#8221;, which is a great book &#8211; not only about the callbacks, but about a host of information.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevoke.net/blog/2010/03/31/ruby-callbacks-hooks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New gem: ListBrowser</title>
		<link>http://trevoke.net/blog/2010/01/15/new-gem-listbrowser/</link>
		<comments>http://trevoke.net/blog/2010/01/15/new-gem-listbrowser/#comments</comments>
		<pubDate>Sat, 16 Jan 2010 00:01:19 +0000</pubDate>
		<dc:creator>Trevoke</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[gem]]></category>
		<category><![CDATA[listbrowser]]></category>

		<guid isPermaLink="false">http://trevoke.net/blog/?p=209</guid>
		<description><![CDATA[~~~~ ListBrowser README ~~~~ I was working on a parser for a very specific tree structure, and was frustrated that there wasn’t a simple way to parse it in irb. &#8220;What??&#8221;, I thought. &#8220;I have to use my brain?! God forbid!&#8221;. So I set to using my brain a little more to create this tool. <a href='http://trevoke.net/blog/2010/01/15/new-gem-listbrowser/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>~~~~ ListBrowser README ~~~~</p>
<p>I was working on a parser for a very specific tree structure, and was frustrated that there wasn’t a simple way to parse it in irb. &#8220;What??&#8221;, I thought. &#8220;I have to use my brain?! God forbid!&#8221;. So I set to using my brain a little more to create this tool. It’s not much, but maybe it’ll make someone’s life a little easier.</p>
<p>Install: (set up gemcutter)<br />
gem install ListBrowser</p>
<p>It can be used in irb, and really should be used there &#8211; when you call it on a tree structure, you’ll get a menu with a list of choices on how you want to go through whatever structure you gave it.</p>
<p>In my particular, special case, I would do something like this:</p>
<p>require ‘sgf_parser’ # For my tree structure require ‘list_browser’ # For this.</p>
<p>tree = SgfParser::Tree.new :filename => &#8220;kogo.sgf&#8221;</p>
<p>ListBrowser.new tree.root, ‘parent’, ‘children’, ‘properties’</p>
<p># And follow the menu!</p>
<p> In my particular case, I would not need to enter those strings, as they<br />
 just happen to be the names I chose for my tree structure, but they should<br />
 serve as a good enough example!</p>
]]></content:encoded>
			<wfw:commentRss>http://trevoke.net/blog/2010/01/15/new-gem-listbrowser/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby SgfParser now really working!</title>
		<link>http://trevoke.net/blog/2009/12/31/ruby-sgfparser-now-really-working/</link>
		<comments>http://trevoke.net/blog/2009/12/31/ruby-sgfparser-now-really-working/#comments</comments>
		<pubDate>Thu, 31 Dec 2009 18:18:51 +0000</pubDate>
		<dc:creator>Trevoke</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[weiqi]]></category>
		<category><![CDATA[baduk]]></category>
		<category><![CDATA[go]]></category>
		<category><![CDATA[sgf]]></category>

		<guid isPermaLink="false">http://trevoke.net/blog/?p=207</guid>
		<description><![CDATA[Thanks @alfmikula, it saves properly and has even been gemified. I will soon push it to gemcutter and maybe put a homesite on Rubyforge, not sure. It can be found at http://github.com/Trevoke/SGFParser for now, get the code while it&#8217;s hot!]]></description>
			<content:encoded><![CDATA[<p>Thanks @alfmikula, it saves properly and has even been gemified. I will soon push it to gemcutter and maybe put a homesite on Rubyforge, not sure.<br />
It can be found at http://github.com/Trevoke/SGFParser for now, get the code while it&#8217;s hot! <img src='http://trevoke.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://trevoke.net/blog/2009/12/31/ruby-sgfparser-now-really-working/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Random constrained permutations in Ruby</title>
		<link>http://trevoke.net/blog/2009/12/17/random-constrained-permutations-in-ruby/</link>
		<comments>http://trevoke.net/blog/2009/12/17/random-constrained-permutations-in-ruby/#comments</comments>
		<pubDate>Thu, 17 Dec 2009 18:50:20 +0000</pubDate>
		<dc:creator>Trevoke</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[permutations]]></category>

		<guid isPermaLink="false">http://trevoke.net/blog/?p=199</guid>
		<description><![CDATA[Look, Ma, these are my baby steps in algorithms!]]></description>
			<content:encoded><![CDATA[<p>Look, Ma, these are my baby steps in algorithms!</p>
<pre class="brush: ruby; title: ; notranslate"># list is the elements to be permuted
# y is the number of results desired
# z is the number of elements per result
# equalizer keeps track of who got used how many times
def constrained_permutations list, y, z
  list.uniq! # Never trust the user. We want no repetitions.
  equalizer = {}
  list.each { |element| equalizer[element] = 0 }

  results = []
  # Do this until we get as many results as desired
  while results.size &lt; y
    pool = []
    puts pool
    least_used = equalizer.each_value.min
    # Find how used the least used element was
    while pool.size &lt; z
      # Do this until we have enough elements in this resultset
      element = nil
      while element.nil?
        # If we run out of &quot;least used elements&quot;, then we need to increment
        # our definition of &quot;least used&quot; by 1 and keep going.
        element = list.shuffle.find do |x|
          !pool.include?(x) &amp;&amp; equalizer[x] == least_used
        end
        least_used += 1 if element.nil?
      end
      equalizer[element] += 1
      # This element has now been used one more time.
      pool &lt;&lt; element
    end
    results &lt;&lt; pool
  end
  return results
end

constrained_permutations [0,1,2,3,4,5,6], 6, 2
=&gt; [[4, 0], [1, 3], [2, 5], [6, 0], [2, 5], [3, 6]]
constrained_permutations [0,1,2,3,4,5,6], 6, 2
=&gt; [[4, 5], [6, 3], [0, 2], [1, 6], [5, 4], [3, 0]]
</pre>
]]></content:encoded>
			<wfw:commentRss>http://trevoke.net/blog/2009/12/17/random-constrained-permutations-in-ruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inter-array permutations in Ruby</title>
		<link>http://trevoke.net/blog/2009/12/17/inter-array-permutations-in-ruby/</link>
		<comments>http://trevoke.net/blog/2009/12/17/inter-array-permutations-in-ruby/#comments</comments>
		<pubDate>Thu, 17 Dec 2009 17:51:06 +0000</pubDate>
		<dc:creator>Trevoke</dc:creator>
				<category><![CDATA[food for thought]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[permutations]]></category>

		<guid isPermaLink="false">http://trevoke.net/blog/?p=193</guid>
		<description><![CDATA[I don&#8217;t really have a better name for this. It&#8217;s also not completely clean, but it works. I had, almost a year ago (362 days ago), written a blog post about lexicographic permutations. That was about permutations of elements within one array. Someone on ruby-forum asked about permutations between multiple arrays. I found something in <a href='http://trevoke.net/blog/2009/12/17/inter-array-permutations-in-ruby/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>I don&#8217;t really have a better name for this. It&#8217;s also not completely clean, but it works. I had, almost a year ago (362 days ago), written a blog post about 
<a  href="http://trevoke.net/blog/2008/12/20/lexicographic-permutations-in-ruby" onclick="javascript:pageTracker._trackPageview('/external/trevoke.net/blog/2008/12/20/lexicographic-permutations-in-ruby');" >lexicographic permutations</a>. That was about permutations of elements within one array.<br />
Someone on ruby-forum asked about permutations between multiple arrays. I 
<a  href="http://stackoverflow.com/questions/710670/c-permutation-of-an-array-of-arraylists" onclick="javascript:pageTracker._trackPageview('/external/stackoverflow.com/questions/710670/c-permutation-of-an-array-of-arraylists');" >found something in C#</a>, which I was happy to transcribe to Ruby and tweak a little.</p>
<pre class="brush: ruby; title: ; notranslate">def array_permutations array, index=0
  # index is 0 by default : start at the beginning, more elegant.
  return array[-1] if index == array.size - 1 # Return last element if at end.
  result = []
  array[index].each do |element| # For each array
    array_permutations(array, index + 1).each do |x| # Permute permute permute
      result &lt;&lt; &quot;#{element}, #{x}&quot;
    end
  end
  return result
end</pre>
<p>So, we get this:</p>
<pre class="brush: ruby; title: ; notranslate">first = ['one', 'two']
second = ['three', 'four']
third = 'five', 'six']
result = array_permutations [first, second, third]
=&gt; [&quot;one, three, five&quot;, &quot;one, three, six&quot;, &quot;one, four, five&quot;, &quot;one, four, six&quot;, &quot;two, three, five&quot;, &quot;two, thre
e, six&quot;, &quot;two, four, five&quot;, &quot;two, four, six&quot;]</pre>
<p>Magic!</p>
<p>&#8212;&#8212;<br />
Edit &#8211; of course, my solution is hackish, and someone came up with a quicker and more elegant solution:</p>
<pre class="brush: ruby; title: ; notranslate">def fancy_array_permutation array
  return array[0] if array.size == 1
  first = array.shift
  return first.product( fancy_array_permutation(array) ).map {|x| x.flatten.join(&quot; &quot;)}
end</pre>
<p>This gives the same result as above.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevoke.net/blog/2009/12/17/inter-array-permutations-in-ruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Open source is wide open: Calling RAKE tasks</title>
		<link>http://trevoke.net/blog/2009/12/15/open-source-is-wide-open-calling-rake-tasks/</link>
		<comments>http://trevoke.net/blog/2009/12/15/open-source-is-wide-open-calling-rake-tasks/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 19:38:25 +0000</pubDate>
		<dc:creator>Trevoke</dc:creator>
				<category><![CDATA[rails]]></category>
		<category><![CDATA[rake]]></category>

		<guid isPermaLink="false">http://trevoke.net/blog/?p=189</guid>
		<description><![CDATA[Open source is wide open: Calling RAKE tasks. Good to know.]]></description>
			<content:encoded><![CDATA[<p>
<a  href="http://railsblogger.blogspot.com/2009/03/in-queue_15.html" onclick="javascript:pageTracker._trackPageview('/external/railsblogger.blogspot.com/2009/03/in-queue_15.html');" >Open source is wide open: Calling RAKE tasks</a>.</p>
<p>Good to know.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevoke.net/blog/2009/12/15/open-source-is-wide-open-calling-rake-tasks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>On re-reading old code</title>
		<link>http://trevoke.net/blog/2009/12/09/on-re-reading-old-code/</link>
		<comments>http://trevoke.net/blog/2009/12/09/on-re-reading-old-code/#comments</comments>
		<pubDate>Wed, 09 Dec 2009 17:07:51 +0000</pubDate>
		<dc:creator>Trevoke</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://trevoke.net/blog/?p=185</guid>
		<description><![CDATA[I came across this beauty: This was &#8220;necessary&#8221; because I got an array of one-element arrays back, and I wanted to check whether or not that one element was the same across the array. Three seconds of thinking made me realize that just maybe, I could do this: I -like- Ruby.]]></description>
			<content:encoded><![CDATA[<p>I came across this beauty:</p>
<pre class="brush: ruby; title: ; notranslate">def same_modality? list
  check = list[0][0]
  list.each do |i|
    return false if check != i[0]
  end
  return true
end</pre>
<p>This was &#8220;necessary&#8221; because I got an array of one-element arrays back, and I wanted to check whether or not that one element was the same across the array.</p>
<p>Three seconds of thinking made me realize that just maybe, I could do this:</p>
<pre class="brush: ruby; title: ; notranslate">list.uniq.size == 1</pre>
<p>I -like- Ruby.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevoke.net/blog/2009/12/09/on-re-reading-old-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Auto-vivifying hashes in Ruby</title>
		<link>http://trevoke.net/blog/2009/11/06/auto-vivifying-hashes-in-ruby/</link>
		<comments>http://trevoke.net/blog/2009/11/06/auto-vivifying-hashes-in-ruby/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 13:27:09 +0000</pubDate>
		<dc:creator>Trevoke</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://trevoke.net/blog/?p=178</guid>
		<description><![CDATA[An auto-vivifying hash is a hash that lets you create sub-hashes automatically. This means that the following code becomes possible: This is useful because it reduces the amount of logic in the code. No more &#8220;If sub-hash doesn&#8217;t exist, create it!&#8221; Courtesy of Robert Klemme on www.ruby-forum.com _____ Update: Facets has a way of doing <a href='http://trevoke.net/blog/2009/11/06/auto-vivifying-hashes-in-ruby/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>An auto-vivifying hash is a hash that lets you create sub-hashes automatically. This means that the following code becomes possible:</p>
<pre class="brush: plain; title: ; notranslate">def cnh # silly name &quot;create nested hash&quot;
  Hash.new {|h,k| h[k] = Hash.new(&amp;h.default_proc)}
end
my_hash = cnh
my_hash[1][2][3] = 4
my_hash # =&gt; { 1 =&gt; { 2 =&gt; { 3 =&gt;4 } } }
</pre>
<p>This is useful because it reduces the amount of logic in the code. No more &#8220;If sub-hash doesn&#8217;t exist, create it!&#8221;</p>
<p>Courtesy of Robert Klemme on www.ruby-forum.com</p>
<p>_____</p>
<p>Update:</p>
<p>Facets has a way of doing an auto-vivifying hash, too! Thanks to 
<a  href="http://stackoverflow.com/questions/1503671/ruby-hash-autovivification-facets" onclick="javascript:pageTracker._trackPageview('/external/stackoverflow.com/questions/1503671/ruby-hash-autovivification-facets');" >Stackoverflow</a>.</p>
<div>
<div>
<pre class="brush: plain; title: ; notranslate">
# Monkey patching Hash class:
# File lib/core/facets/hash/autonew.rb, line 19
  def self.autonew(*args)
    leet = lambda { |hsh, key| hsh[key] = new( &amp;leet ) }
    new(*args,&amp;leet)
  end
</pre>
</div>
</div>
<div>
<div>
<div>
<p>The standard 
<a rel="nofollow"  href="http://ruby-doc.org/core/classes/Hash.html#M002840" onclick="javascript:pageTracker._trackPageview('/external/ruby-doc.org/core/classes/Hash.html?M002840');" >new  method for Hash</a> accepts a block. This block is called in the event  of trying to access a key in the Hash which does not exist. The block is  passed the Hash itself and the key that was requested (the two  parameters) and should return the value that should be returned for the  requested key.</p>
<p>You will notice that the <code>leet</code> lambda does 2 things. It  returns a new Hash with <code>leet</code> itself as the block for  handling defaults. This is the behaviour which allows <code>autonew</code> to work for Hashes of arbitrary depth. It also assigns this new Hash to  <code>hsh[key]</code> so that next time you request the same key you  will get the existing Hash rather than a new one being created.</p>
<p>Sweet deal!</p>
</div>
</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://trevoke.net/blog/2009/11/06/auto-vivifying-hashes-in-ruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Closures in Ruby</title>
		<link>http://trevoke.net/blog/2009/10/28/closures-in-ruby/</link>
		<comments>http://trevoke.net/blog/2009/10/28/closures-in-ruby/#comments</comments>
		<pubDate>Wed, 28 Oct 2009 14:22:42 +0000</pubDate>
		<dc:creator>Trevoke</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://trevoke.net/blog/?p=175</guid>
		<description><![CDATA[I found a script that explains everything really well. Credit goes to: # CLOSURES IN RUBY Paul Cantrell http://innig.net # Email: username &#8220;cantrell&#8221;, domain name &#8220;pobox.com&#8221; Along with this blog entry, it&#8217;s made the whole deal much easier to figure out. Now.. Why didn&#8217;t I get that when I was looking at LISP?]]></description>
			<content:encoded><![CDATA[<p>I found a 
<a  href="http://innig.net/software/ruby/closures-in-ruby.rb" onclick="javascript:pageTracker._trackPageview('/external/innig.net/software/ruby/closures-in-ruby.rb');" >script</a> that explains everything really well.<br />
Credit goes to:<br />
# CLOSURES IN RUBY     Paul Cantrell    http://innig.net<br />
# Email: username &#8220;cantrell&#8221;, domain name &#8220;pobox.com&#8221;<br />
Along with 
<a  href="http://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods/" onclick="javascript:pageTracker._trackPageview('/external/eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods/');" >this blog entry</a>, it&#8217;s made the whole deal much easier to figure out.</p>
<p>Now.. Why didn&#8217;t I get that when I was looking at LISP? </p>
]]></content:encoded>
			<wfw:commentRss>http://trevoke.net/blog/2009/10/28/closures-in-ruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.325 seconds -->

