<?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>nearly random &#187; ruby</title>
	<atom:link href="http://www.johnbaylor.org/category/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.johnbaylor.org</link>
	<description>but with a nefarious purpose</description>
	<lastBuildDate>Thu, 10 Dec 2009 20:20:44 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Toothpicks</title>
		<link>http://www.johnbaylor.org/2008/12/21/toothpicks/</link>
		<comments>http://www.johnbaylor.org/2008/12/21/toothpicks/#comments</comments>
		<pubDate>Sun, 21 Dec 2008 19:25:09 +0000</pubDate>
		<dc:creator>JohnB</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.johnbaylor.org/?p=52</guid>
		<description><![CDATA[Intending to direct a new Ruby-ist to rubyquiz.com, I hastily  misread the Counting Toothpicks quiz as the reverse of what was intended.  So here is my quick code to solve the wrong problem: converting a string of toothpicks to its underlying equation and giving the answer. I was quite happy with my short solution [...]]]></description>
			<content:encoded><![CDATA[<p>Intending to direct a new Ruby-ist to <a href="http://rubyquiz.com/">rubyquiz.com</a>, I hastily  misread the <a href="http://rubyquiz.com/quiz111.html">Counting Toothpicks</a> quiz as the reverse of what was intended.  So here is my quick code to solve the wrong problem: converting a string of toothpicks to its underlying equation and giving the answer. I was quite happy with my short solution until realizing that I had solved a much simpler problem. In any case, here it is:</p>
<pre><span class="comment">#</span>
<span class="comment"># toothpicks.rb</span>
<span class="comment">#</span>
<span class="keyword">def </span><span class="method">toothpicks</span> <span class="ident">str</span>
  <span class="ident">puts</span> <span class="ident">str</span>
  <span class="ident">str</span><span class="punct">.</span><span class="ident">gsub!</span><span class="punct">('</span><span class="string"> </span><span class="punct">','</span><span class="punct">')</span>
  <span class="keyword">raise</span> <span class="punct">'</span><span class="string">Wrong format</span><span class="punct">'</span> <span class="keyword">unless</span> <span class="ident">str</span> <span class="punct">=~</span> <span class="punct">/</span><span class="regex">^(x|<span class="escape">\|</span>|<span class="escape">\+</span>|-)*$</span><span class="punct">/</span>
  <span class="ident">count</span> <span class="punct">=</span> <span class="ident">str</span><span class="punct">.</span><span class="ident">length</span>
  <span class="ident">count</span> <span class="punct">+=</span> <span class="ident">str</span><span class="punct">.</span><span class="ident">scan</span><span class="punct">(/</span><span class="regex">(x|<span class="escape">\+</span>)</span><span class="punct">/).</span><span class="ident">length</span>
  <span class="ident">str</span><span class="punct">.</span><span class="ident">length</span><span class="punct">.</span><span class="ident">downto</span><span class="punct">(</span><span class="number">1</span><span class="punct">)</span> <span class="keyword">do</span> <span class="punct">|</span><span class="ident">n</span><span class="punct">|</span>
    <span class="ident">str</span><span class="punct">.</span><span class="ident">gsub!</span><span class="punct">(</span> <span class="punct">'</span><span class="string">|</span><span class="punct">'*</span> <span class="ident">n</span><span class="punct">,</span> <span class="ident">n</span><span class="punct">.</span><span class="ident">to_s</span> <span class="punct">)</span>
  <span class="keyword">end</span>
  <span class="ident">str</span><span class="punct">.</span><span class="ident">gsub!</span><span class="punct">('</span><span class="string">x</span><span class="punct">','</span><span class="string">*</span><span class="punct">')</span>
  <span class="ident">puts</span> <span class="ident">str</span>
  <span class="ident">result</span> <span class="punct">=</span> <span class="ident">eval</span><span class="punct">(</span><span class="ident">str</span><span class="punct">)</span>
  <span class="ident">puts</span> <span class="punct">"</span><span class="string"><span class="expr">#{result}</span> from <span class="expr">#{count}</span> toothpicks</span><span class="punct">"</span>
<span class="keyword">end</span>

<span class="keyword">if</span> <span class="constant">ARGV</span><span class="punct">[</span><span class="number">0</span><span class="punct">]</span>
  <span class="ident">toothpicks</span> <span class="constant">ARGV</span><span class="punct">[</span><span class="number">0</span><span class="punct">].</span><span class="ident">dup</span>
<span class="keyword">else</span>
  <span class="ident">toothpicks</span> <span class="punct">'</span><span class="string">||| x || + ||||| - |||||||</span><span class="punct">'</span>
<span class="keyword">end</span></pre>
<p>Running with no arguments tests the example equation:</p>
<pre>&gt;&gt;toothpicks.rb
||| x || + ||||| - |||||||
3*2+5-7
4 from 22 toothpicks</pre>
<p>Note: syntax highlighting provided by <a href="http://www.rubyinside.com/advent2006/7-coloring.html">this nice page</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.johnbaylor.org/2008/12/21/toothpicks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>unpack!</title>
		<link>http://www.johnbaylor.org/2008/02/27/u/</link>
		<comments>http://www.johnbaylor.org/2008/02/27/u/#comments</comments>
		<pubDate>Wed, 27 Feb 2008 07:54:16 +0000</pubDate>
		<dc:creator>JohnB</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.johnbaylor.org/2008/02/27/u/</guid>
		<description><![CDATA[[Update 10/11/2009: I just found a better tool, bindata, to do what I'm describing in this post. It also lists, at the bottom of the page, many links to yet other implementations of binary data packing/unpacking. Worth checking out if this is what you need.]
[Update: presentation from the 4/15/2008 Ruby Meetup is now available here.]
I like reading [...]]]></description>
			<content:encoded><![CDATA[<p>[Update 10/11/2009: I just found a better tool, <a href="http://bindata.rubyforge.org/">bindata</a>, to do what I'm describing in this post. It also lists, at the bottom of the page, many links to yet other implementations of binary data packing/unpacking. Worth checking out if this is what you need.]</p>
<p>[Update: presentation from the <a href="http://ruby.meetup.com/81/calendar/7577430/" target="_blank">4/15/2008 Ruby Meetup</a> is now available <a href="http://docs.google.com/Presentation?id=ad9wfpzzrhx_46fnbpqrgx" target="_blank">here</a>.]</p>
<p>I like reading code. Its like a novel and I want to read it cover-to-cover. Some, such as <a title="why not" href="http://en.wikipedia.org/wiki/Why_the_lucky_stiff">Why&#8217;s</a> <a title="The full source code, with many many comments." href="http://github.com/camping/camping/blob/master/lib/camping-unabridged.rb">Camping framework</a>, I struggle to comprehend. But most code that I read comes up slightly short. Like a novel with some mis-spellings, awkward phrasing or repeated analogies, I mentally mark it as &#8220;could be better&#8221;. And sometimes I really do sit down and write something better &#8211; maybe just for my own amusement but often for a useful purpose.</p>
<p>I recently had the experience of reading some code that parsed a variable-length binary data structure. This sort of thing comes up often when parsing a file format or communications protocol. Most of the code looks fairly similar because it does similar stuff: ignore one byte, read the next four as the length of the following junk, read two important bytes, ignore two more, read another four-byte length and skip past the following N bytes &#8211; ad nauseum.</p>
<p>I&#8217;ve written it in C, and it looks something like this (ignoring error conditions like getting to the end of the buffer):</p>
<pre>ptr = &amp;data;                  // start at the beginning of our data
ptr++;                        // skip junk we don't care about
UInt32 len = *(UInt32 *) ptr; // get the 4-byte length
len = ntohl(len);             // convert from network byte ordering
ptr += sizeof(UInt32);        // skip past the length we just read
ptr += len;                   // skip past the data we don't care about
UInt16 cost = *(UInt16 *)ptr; // read our important two bytes
cost = ntohs(cost);           // convert to the correct byte ordering</pre>
<p>In Ruby, this tends to be shorter due to the handy String.unpack() routine, which takes a concise format string to define how many bytes to read and what to do with them. &#8220;a3&#8243; reads 3 bytes as a string, &#8220;N&#8221; reads 4 bytes in network order, &#8220;n&#8221; reads 2 bytes in network order, etc. The code above could be rewritten in Ruby like this:</p>
<pre><span class="ident">array</span> <span class="punct">=</span> <span class="ident">data</span><span class="punct">.</span><span class="ident">unpack</span><span class="punct">(</span> <span class="punct">"</span><span class="string">a1N</span><span class="punct">")</span>        <span class="comment"># read the junk and the 4 length bytes</span>
<span class="ident">len</span> <span class="punct">=</span> <span class="ident">array</span><span class="punct">[</span><span class="number">1</span><span class="punct">]</span>                     <span class="comment"># only get the length value we care about</span>
<span class="ident">data</span> <span class="punct">=</span> <span class="ident">data</span><span class="punct">[</span><span class="number">5</span><span class="punct">..-</span><span class="number">1</span><span class="punct">]</span>                 <span class="comment"># throw away the stuff we just read</span>
<span class="ident">array</span> <span class="punct">=</span>  <span class="ident">data</span><span class="punct">.</span><span class="ident">unpack</span><span class="punct">(</span> <span class="punct">"</span><span class="string">a<span class="expr">#{len}</span>n</span><span class="punct">"</span> <span class="punct">)</span> <span class="comment"># define the length to read on the fly</span>
<span class="ident">cost</span> <span class="punct">=</span> <span class="ident">array</span><span class="punct">[</span><span class="number">1</span><span class="punct">]</span>                    <span class="comment"># get our data in its correct ordering</span>
<span class="ident">data</span> <span class="punct">=</span> <span class="ident">data</span><span class="punct">[(</span><span class="ident">len</span><span class="punct">+</span><span class="number">2</span><span class="punct">)..-</span><span class="number">1</span><span class="punct">]</span>           <span class="comment"># again, throw away what we just read</span></pre>
<p>This code works fine, but its not much more readable than the C code. A first step would be do define a string.unpack!() routine, where the &#8216;!&#8217; exclamation clues us in that it modifies the object we&#8217;re working with. In this case, the modification is to <span style="font-style: italic">eat</span> (discard) the data we just read. This shortens the code to:</p>
<pre><span class="ident">array</span> <span class="punct">=</span> <span class="ident">data</span><span class="punct">.</span><span class="ident">unpack!</span><span class="punct">(</span> <span class="punct">"</span><span class="string">a1N</span><span class="punct">")</span>       <span class="comment"># read the junk and the 4 length bytes</span>
<span class="ident">len</span> <span class="punct">=</span> <span class="ident">array</span><span class="punct">[</span><span class="number">1</span><span class="punct">]</span>                     <span class="comment"># only get the length value we care about</span>
<span class="ident">array</span> <span class="punct">=</span>  <span class="ident">data</span><span class="punct">.</span><span class="ident">unpack!</span><span class="punct">("</span><span class="string">a<span class="expr">#{len}</span>n</span><span class="punct">")</span>  <span class="comment"># define the length to read on the fly</span>
<span class="ident">cost</span> <span class="punct">=</span> <span class="ident">array</span><span class="punct">[</span><span class="number">1</span><span class="punct">]</span>                    <span class="comment"># get our data in its correct ordering</span></pre>
<p>But again, this isn&#8217;t much more readable (in my opinion) than the C code. Additionally, it doesn&#8217;t help us understand the code much better in the case where our format string is &#8220;a3Nna5&#8243; and we need to remember which item in &#8216;array&#8217; corresponds to the &#8216;n&#8217; in the string (in this case, it is array[2]). After a test iteration or two, what I finally hit upon was to encapsulate the behavior we want in a separare Unpacker class, that automatically eats the data it reads and stores the results in an internal Hash object, to map the name &#8216;len&#8217; or &#8216;cost&#8217; to the data. I also combined the format string and the resulting variable so we can clearly see the relationships. The result looks like this:</p>
<pre><span class="ident">u</span> <span class="punct">=</span> <span class="constant">Unpacker</span><span class="punct">.</span><span class="ident">new</span><span class="punct">(</span><span class="ident">data</span><span class="punct">)</span>
<span class="ident">u</span><span class="punct">.</span><span class="ident">u!</span> <span class="punct">"</span><span class="string">a1        =&gt; unused
      N         =&gt; len</span><span class="punct">"</span>
<span class="ident">u</span><span class="punct">.</span><span class="ident">u!</span> <span class="punct">"</span><span class="string">a<span class="expr">#{u.len}</span> =&gt; unused
      n         =&gt; cost</span><span class="punct">"</span></pre>
<p>Now we can clearly see which values are ignored, which are given meaningful names, and how the format codes relate to the meaning of the data. Changing it to reflect a better understanding of the underlying data will be very easy. Note that the only reason its in two statements is to define a value for u.len before we use it &#8211; blocks of fixed-length data can be one statement.</p>
<p>The code to implement the Unpacker class is only about 30 lines of Ruby &#8211; including the string.unpack!() routine that can be reused separately.</p>
<pre><span class="keyword">class </span><span class="class">String</span>
  <span class="keyword">def </span><span class="method">unpack!</span> <span class="ident">format</span>
     <span class="ident">array</span> <span class="punct">=</span> <span class="constant">self</span><span class="punct">.</span><span class="ident">unpack</span><span class="punct">(</span><span class="ident">format</span><span class="punct">+"</span><span class="string">a*</span><span class="punct">")</span>
    <span class="constant">self</span><span class="punct">.</span><span class="ident">replace</span> <span class="ident">array</span><span class="punct">.</span><span class="ident">pop</span>
     <span class="keyword">return</span> <span class="ident">array</span>
   <span class="keyword">end</span>
<span class="keyword">end</span>
<span class="keyword">class </span><span class="class">Unpacker</span> <span class="punct">&lt;</span> <span class="constant">Hash</span>
   <span class="ident">attr_reader</span> <span class="symbol">:data</span>
 <span class="keyword">def </span><span class="method">initialize</span> <span class="ident">string</span>
     <span class="attribute">@data</span> <span class="punct">=</span> <span class="ident">string</span>
    <span class="keyword">super</span>
  <span class="keyword">end</span>
  <span class="comment"># format string is expected to have whitespace between each</span>
  <span class="comment"># "unpackCode=&gt;variableName" pairing (which can have whitespace</span>
  <span class="comment"># around the "=&gt;").  u! was picked to be short so it would</span>
  <span class="comment"># look nice, and to connote a destructive "unpack!" operation.</span>
  <span class="keyword">def </span><span class="method">u!</span> <span class="ident">format</span>
    <span class="ident">format</span><span class="punct">.</span><span class="ident">gsub</span><span class="punct">(/</span><span class="regex"><span class="escape">\s</span>*=&gt;<span class="escape">\s</span>*</span><span class="punct">/,'</span><span class="string">=&gt;</span><span class="punct">').</span><span class="ident">strip</span><span class="punct">.</span><span class="ident">split</span><span class="punct">(/</span><span class="regex"><span class="escape">\s</span>+</span><span class="punct">/).</span><span class="ident">each</span> <span class="keyword">do</span> <span class="punct">|</span><span class="ident">segment</span><span class="punct">|</span>
    <span class="ident">src</span><span class="punct">,</span><span class="ident">dst</span> <span class="punct">=</span> <span class="ident">segment</span><span class="punct">.</span><span class="ident">split</span><span class="punct">(/</span><span class="regex">=&gt;</span><span class="punct">/)</span>
    <span class="constant">self</span><span class="punct">[</span><span class="ident">dst</span><span class="punct">]</span> <span class="punct">=</span> <span class="attribute">@data</span><span class="punct">.</span><span class="ident">unpack!</span><span class="punct">("</span><span class="string"><span class="expr">#{src}</span></span><span class="punct">")[</span><span class="number">0</span><span class="punct">]</span>
 <span class="keyword">end</span>
<span class="keyword">end</span>
<span class="comment"># Hash_with_Attrs - For the simplicity of using either u.len or u['len'],</span>
<span class="comment"># makes a hash appear to have members for each hash entry. Many thanks</span>
<span class="comment"># to Why_ for collecting this handy routine on his a href= RedHanded blog.</span>
<span class="comment"># Note of Caution: 'len' is fine but 'length' would not be since u.length</span>
<span class="comment"># would give the number of entries in the hash, not the just-parsed value.</span>
<span class="keyword">def </span><span class="method">method_missing</span><span class="punct">(</span><span class="ident">meth</span><span class="punct">,*</span><span class="ident">args</span><span class="punct">)</span>
  <span class="ident">meth</span> <span class="punct">=</span> <span class="ident">meth</span><span class="punct">.</span><span class="ident">id2name</span>
  <span class="keyword">if</span> <span class="ident">meth</span> <span class="punct">=~</span> <span class="punct">/</span><span class="regex">=$</span><span class="punct">/</span>
    <span class="constant">self</span><span class="punct">[</span><span class="ident">meth</span><span class="punct">[</span><span class="number">0</span><span class="punct">..-</span><span class="number">2</span><span class="punct">]]</span> <span class="punct">=</span> <span class="punct">(</span><span class="ident">args</span><span class="punct">.</span><span class="ident">length</span><span class="punct">&lt;</span><span class="number">2</span> <span class="punct">?</span> <span class="ident">args</span><span class="punct">[</span><span class="number">0</span><span class="punct">]</span> <span class="punct">:</span> <span class="ident">args</span><span class="punct">)</span>
  <span class="keyword">else</span>
    <span class="constant">self</span><span class="punct">[</span><span class="ident">meth</span><span class="punct">]</span>
  <span class="keyword">end</span>
<span class="keyword">end</span>
<span class="keyword">end</span></pre>
<p>Update: <em>An even cleaner and shorter way would be to implement a <a href="http://en.wikipedia.org/wiki/Domain-specific_programming_language">DSL</a> as a module so the code above could look like this:</em></p>
<pre><span class="ident">a</span> <span class="number">1</span><span class="punct">,</span>    <span class="symbol">:unused</span>
<span class="constant">N</span>       <span class="symbol">:len</span>
<span class="ident">a</span> <span class="symbol">:len</span><span class="punct">,</span> <span class="symbol">:unused</span>
<span class="ident">n</span>       <span class="symbol">:cost</span></pre>
<p><em>(and yes, this is valid Ruby code)</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.johnbaylor.org/2008/02/27/u/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Xkcd Titles</title>
		<link>http://www.johnbaylor.org/2008/01/14/xkcd-titles/</link>
		<comments>http://www.johnbaylor.org/2008/01/14/xkcd-titles/#comments</comments>
		<pubDate>Mon, 14 Jan 2008 20:26:04 +0000</pubDate>
		<dc:creator>JohnB</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.johnbaylor.org/2008/01/14/xkcd-titles/</guid>
		<description><![CDATA[I&#8217;ve just noticed the geekily hilarious xkcd comic and one of the funniest aspects is that each comic has a &#8216;title&#8217; attribute (the text that pops up when you hover your mouse over the image) that is often as funny as the comic itself.  However, the length of the title often causes it to [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just noticed the <a href="http://xkcd.com/249/" title="Yes, I play blindfold chess; it says so on my resume">geekily</a> <a href="http://xkcd.com/234/" title="You see, when unix gets confused by spaces, you can tell it to ignore the space by "escaping" it with a backslash which is a pun on... oh, never mind">hilarious</a> <a href="http://xkcd.com/" title="Click the link, dummy!">xkcd comic</a> and one of the funniest aspects is that each comic has a &#8216;title&#8217; attribute (the text that pops up when you hover your mouse over the image) that is often as funny as the comic itself.  However, the length of the title often causes it to be truncated in my browser (Firefox 2.x, which probably has an obscure show-entire-title setting).  Rather than arduously do a &#8216;view source&#8217; on each one (or figure out the Firefox setting), I have Ruby do it for me.  And for <em>you</em> if you want:</p>
<pre>
# xkcd.rb
# extract all the titles from xkcd comics since they
# tend to be too long to fully show in the browser

# USAGE: ruby -rubygems -rxkcd.rb -e 'Xkcd.new.show_all'

require 'open-uri'
require 'hpricot'

class Xkcd
  DOMAIN = 'http://xkcd.com/'

  def show id = 343  # 343 is the NSA/RSA one
    begin
      @hp = Hpricot.parse( open( "%s/%d/" % [DOMAIN,id.to_i] ) )
      (@hp / :img).each do |el|
        puts "%4d: %s" % [id.to_i, el[:title]] if el[:title]
      end
    rescue
    end
  end

  def show_all
    0.upto(400) do |i|
      show i
    end
  end
end</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.johnbaylor.org/2008/01/14/xkcd-titles/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Iterators &#8211; enough of a reason for Ruby</title>
		<link>http://www.johnbaylor.org/2007/10/11/iterators-enough-of-a-reason-for-ruby/</link>
		<comments>http://www.johnbaylor.org/2007/10/11/iterators-enough-of-a-reason-for-ruby/#comments</comments>
		<pubDate>Thu, 11 Oct 2007 22:09:20 +0000</pubDate>
		<dc:creator>JohnB</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.johnbaylor.org/2007/10/11/iterators-enough-of-a-reason-for-ruby/</guid>
		<description><![CDATA[A non-programmer friend recently asked me why I liked Ruby so much.  I asked him for a simple task that I could write in Ruby and we came up with a pyramid &#8211; from a single &#8220;a&#8221; to 26 &#8220;z&#8221;s.  So I showed him this one-liner:
"a".upto("z") { &#124;c&#124; puts c * (1 + [...]]]></description>
			<content:encoded><![CDATA[<p>A non-programmer friend recently asked me why I liked Ruby so much.  I asked him for a simple task that I could write in Ruby and we came up with a pyramid &#8211; from a single &#8220;a&#8221; to 26 &#8220;z&#8221;s.  So I showed him this one-liner:</p>
<pre>"a".upto("z") { |c| puts c * (1 + c[0] - "a"[0]) }</pre>
<p>And then showed him the same program in C:</p>
<pre>#include "stdio.h"
int main( int argc, char **argv )
{
  int loop = 0;
  for( loop = 0; loop &lt; 26; loop++ )
  {
    int innerloop = 0;
    for( innerloop = 0; innerloop &lt;= loop; innerloop++ )
    {
      printf( "%c", 'a' + loop );
    }
    printf("n");
  }
  return 0;
}</pre>
<p>Enough said.</p>
<pre>a
bb
ccc
dddd
eeeee
ffffff
ggggggg
hhhhhhhh
iiiiiiiii
jjjjjjjjjj
kkkkkkkkkkk
llllllllllll
mmmmmmmmmmmmm
nnnnnnnnnnnnnn
ooooooooooooooo
pppppppppppppppp
qqqqqqqqqqqqqqqqq
rrrrrrrrrrrrrrrrrr
sssssssssssssssssss
tttttttttttttttttttt
uuuuuuuuuuuuuuuuuuuuu
vvvvvvvvvvvvvvvvvvvvvv
wwwwwwwwwwwwwwwwwwwwwww
xxxxxxxxxxxxxxxxxxxxxxxx
yyyyyyyyyyyyyyyyyyyyyyyyy
zzzzzzzzzzzzzzzzzzzzzzzzzz</pre>
<p><em>2/6/2008 Update: </em>it might be shorter and more clear like this</p>
<pre>("a".."z").each_with_index { |c,i| puts (c * (i + 1)) }</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.johnbaylor.org/2007/10/11/iterators-enough-of-a-reason-for-ruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>d efine for twitter &#8211; step 1</title>
		<link>http://www.johnbaylor.org/2007/09/29/d-efine-for-twitter-step-1/</link>
		<comments>http://www.johnbaylor.org/2007/09/29/d-efine-for-twitter-step-1/#comments</comments>
		<pubDate>Sat, 29 Sep 2007 21:55:33 +0000</pubDate>
		<dc:creator>JohnB</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.johnbaylor.org/2007/09/29/d-efine-for-twitter-step-1/</guid>
		<description><![CDATA[For those of you who use twitter, you&#8217;ll likely recognize the separation of &#8216;d&#8217; from &#8216;efine&#8217; as intentional: &#8216;d&#8217; means direct a message to another twitter user and &#8216;efine&#8217; is the user you&#8217;re sending it to.  Together I hope they connote &#8216;define&#8217; because thats what they do. Sending
d efine ruby
to twitter should, if my [...]]]></description>
			<content:encoded><![CDATA[<p>For those of you who use twitter, you&#8217;ll likely recognize the separation of &#8216;d&#8217; from &#8216;efine&#8217; as intentional: &#8216;d&#8217; means direct a message to another twitter user and &#8216;efine&#8217; is the user you&#8217;re sending it to.  Together I hope they connote &#8216;define&#8217; because thats what they do. Sending</p>
<pre>d efine ruby</pre>
<p>to twitter should, if my twitter-bot works as intended, return a direct reply of</p>
<pre>"A clear, deep, red, valued as a precious stone."</pre>
<p>Which is a fairly accurate definition (even if it <em>does </em>leave out my favorite computer language).</p>
<p>So in this part I&#8217;ll describe the definition-grabbing piece, which queries <a href="http://en.wiktionary.org/wiki/java" title="wiktionary.org" target="_blank">wiktionary.org</a> for the first definition.  This first iteration is stupidly simple: read the entire page, parse its contents with the wondrous <a href="http://code.whytheluckystiff.net/hpricot/" title="_why oh _why" target="_blank">Hpricot</a> tool, grab the first item from the first ordered list on the page and throw away any links.  It sometimes gets odd or partial definitions so it will need improvement &#8211; but works great for the five minutes it took to write.</p>
<pre>
require 'open-uri'
require 'hpricot'
def efine word
  open("http://en.wiktionary.org/wiki/#{word}") do |f|
    (Hpricot(f.read) / "ol" / "li")[0].to_plain_text.gsub(/s*[.*]/,'')
  end
end</pre>
<p>That&#8217;s all.  You&#8217;ll have to wait for the twitter-integration piece in my next post.  I haven&#8217;t written it yet, but given the functionality in <a href="http://twitter4r.rubyforge.org/" title="twitter API for Ruby" target="_blank">twitter4r</a>, I doubt it will be much longer than the efine() method above.  In fact, my usual peeve about Ruby is just that: it takes longer to describe the code than to write it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.johnbaylor.org/2007/09/29/d-efine-for-twitter-step-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RJS Error: TypeError: $(element) has no properties</title>
		<link>http://www.johnbaylor.org/2007/09/21/rjs-error-typeerror-element-has-no-properties/</link>
		<comments>http://www.johnbaylor.org/2007/09/21/rjs-error-typeerror-element-has-no-properties/#comments</comments>
		<pubDate>Sat, 22 Sep 2007 01:11:34 +0000</pubDate>
		<dc:creator>JohnB</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.johnbaylor.org/2007/09/21/rjs-error-typeerror-element-has-no-properties/</guid>
		<description><![CDATA[I received this error message late yesterday while testing out RJS templates and link_to_remote().  I did a google search and didn&#8217;t find anything useful &#8211; some questions that were asked and never answered; one that said &#8220;rebuild your entire app&#8221;.  Finally, I opened the page in another browser and it worked fine.  [...]]]></description>
			<content:encoded><![CDATA[<p>I received this error message late yesterday while testing out RJS templates and link_to_remote().  I did a google search and didn&#8217;t find anything useful &#8211; some questions that were asked and never answered; one that said &#8220;rebuild your entire app&#8221;.  Finally, I opened the page in another browser and it worked fine.  huh?</p>
<p>doh!  Rails nearly-seamless simplicity strikes again!</p>
<p>I had just changed my view code (.rhtml file) to include a new div that I wanted to be updated in an AJAXy manner.  So I clicked the link in the browser (remember: this is AJAX &#8211; no page refresh) and expected my new div to be replaced with the neat new content.  Nope.  I had to do a decidedly non-AJAX page refresh so my browser would now <em>have</em> the neat new div &#8211; only then could the div be replaced.</p>
<p>Its so simple to swap between edit and test, edit and test, edit and test, that the few times you&#8217;re required to step out of the cycle seem like a huge hassle.  But not when compared to every <em>other</em>  development process I&#8217;ve used.</p>
<p>I had a similar experience with the routes.rb file.  Unlike models and controllers and non-AJAX views, the routes.rb file only gets loaded when the web server starts.  Stopping and starting the server fixed the problem &#8211; but I think I had to run into it multiple times before I realized what the issue was.  A minor pot-hole on the smooth Rails path.</p>
<p>To mis-quote a bumper sticker: the worst day coding Ruby is better than the best day fighting C++.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.johnbaylor.org/2007/09/21/rjs-error-typeerror-element-has-no-properties/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>irb tip</title>
		<link>http://www.johnbaylor.org/2007/08/07/irb-tip/</link>
		<comments>http://www.johnbaylor.org/2007/08/07/irb-tip/#comments</comments>
		<pubDate>Tue, 07 Aug 2007 22:04:54 +0000</pubDate>
		<dc:creator>JohnB</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.johnbaylor.org/2007/08/07/irb-tip/</guid>
		<description><![CDATA[Have you ever loaded a file into irb, only to find that it scrolls endlessly?  Its easy to do by accident:
log = File.open('bigger_file_than_you_expected.log') { &#124;f&#124; f.read }
But a simple trick can limit the output to a single useful line:
(log = File.open('bigger_file_than_you_expected.log') { &#124;f&#124; f.read }).length
=&#62; 5066612
Now you can happily slice and dice your data [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever loaded a file into irb, only to find that it scrolls endlessly?  Its easy to do by accident:</p>
<pre>log = File.open('bigger_file_than_you_expected.log') { |f| f.read }</pre>
<p>But a simple trick can limit the output to a single useful line:</p>
<pre>(log = File.open('bigger_file_than_you_expected.log') { |f| f.read }).length</pre>
<pre>=&gt; 5066612</pre>
<p>Now you can happily slice and dice your data without all the useless output.  And yes, it applies to any operation that would spit out more data than you really want to see.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.johnbaylor.org/2007/08/07/irb-tip/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails Drop-In: tooltip.rb</title>
		<link>http://www.johnbaylor.org/2007/08/05/rails-drop-in-tooltiprb/</link>
		<comments>http://www.johnbaylor.org/2007/08/05/rails-drop-in-tooltiprb/#comments</comments>
		<pubDate>Mon, 06 Aug 2007 06:41:49 +0000</pubDate>
		<dc:creator>JohnB</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.johnbaylor.org/2007/08/05/rails-drop-in-tooltiprb/</guid>
		<description><![CDATA[I recently came across Davey Shafik&#8217;s nice little Tooltip.js script &#8211; and I love it.  I love it so much that I&#8217;m adding it as context-sensitive help all over the site I&#8217;m building.  My needs are fairly simple: just some sort of pseudo-icon I can use next to any visual element to show [...]]]></description>
			<content:encoded><![CDATA[<p>I recently came across Davey Shafik&#8217;s nice little <a href="http://tooltip.crtx.org/">Tooltip.js script</a> &#8211; and I love it.  I love it so much that I&#8217;m adding it as context-sensitive help all over the site I&#8217;m building.  My needs are fairly simple: just some sort of pseudo-icon I can use next to any visual element to show that help or warning information is available.  Every aspect can (of course!) be styled any way you want it.</p>
<p>To gain consistency and ease of use I wrote something that isn&#8217;t an actual Rails plug-in but is more of a&#8230; drop-in.  Just drop in three files and you&#8217;re ready to roll.  There are a few ways to add the tips to your views, but the easiest way is to just add</p>
<pre>
&lt;%= Tooltip.help name %&gt;</pre>
<p>or</p>
<pre>
&lt;%= Tooltip.alert name %&gt;</pre>
<p>to show a highlighted icon.  The ones I currently use are html pseudo-icons (<strong id="tooltip_activator_help" style="background-color: yellow; vertical-align: super">?</strong> for help and <strong id="tooltip_activator_remember_me" style="background-color: orange; vertical-align: super">!</strong> for warnings) but they can just as easily be image tags (and will be, as soon as I can find some appropriate icons).</p>
<p>Finally, to get the tip data to be formatted into hidden divs you need to add this to the bottom of your view (or, ideally, your layout):</p>
<pre>
&lt;%= Tooltip.content %&gt;</pre>
<p>Thats nearly all there is to it.  The only remaining task is to add these three files:</p>
<table>
<tr>
<td>
<pre><a href="http://tooltip.crtx.org/">public/javascripts/Tooltip.js</a></pre>
</td>
<td>Davey&#8217;s code.</td>
</tr>
<tr>
<td>
<pre>/lib/tooltip.rb</pre>
</td>
<td>My code.</td>
</tr>
<tr>
<td>
<pre>/config/tooltips.yaml</pre>
</td>
<td>Styles and the tip contents.</td>
</tr>
</table>
<p>Eventually I&#8217;ll make it publicly available, but if you&#8217;d like a copy sooner just send me a note at my gmail address: john dot baylor.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.johnbaylor.org/2007/08/05/rails-drop-in-tooltiprb/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
