<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>Talk Like A Duck: Category ruby</title>
    <link>http://talklikeaduck.denhaven2.com/articles/category/ruby</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>In Ruby, it's not the dog, it's the tricks!</description>
    <item>
      <title>Solving the Final Google Treasure Hunt Problem in Ruby</title>
      <description>For the past four weeks, Google has been running the &lt;a href="http://treasurehunt.appspot.com/"&gt;2008 Google Treasure Hunt&lt;/a&gt;. Each Monday a new question
was asked, requiring a &amp;#8216;simple&amp;#8217; answer.  Actually, each question was parameterized, and the parameters were &amp;#8216;randomly&amp;#8217; generated for each participant.
&lt;p&gt;For each of the four questions, I wrote a Ruby program to find the answer.&lt;/p&gt;
&lt;p&gt;The final question was probably the hardest, and although it&amp;#8217;s still &amp;#8216;alive&amp;#8217;, the spoilers have already started to appear on the internets. &lt;a href="http://www.catonmat.net/blog/solving-google-treasure-hunt-prime-number-problem-four/"&gt;Peter Krumins has posted a solution using unix shell commands,&lt;/a&gt; so I figured I&amp;#8217;d show my Ruby solution&lt;/p&gt;
&lt;h2&gt;The Problem&lt;/h2&gt;
&lt;p&gt;As Peter describes the problem is to find the smallest prime number which can be expressed as a sum of several different numbers of consecutive primes. Here&amp;#8217;s the question as Google posed it to me:&lt;/p&gt;
&lt;quote&gt;Find the smallest number that can be expressed as
&lt;p&gt;the sum of 3 consecutive prime numbers,&lt;/p&gt;
&lt;p&gt;the sum of 5 consecutive prime numbers,&lt;/p&gt;
&lt;p&gt;the sum of 275 consecutive prime numbers,&lt;/p&gt;
&lt;p&gt;the sum of 1167 consecutive prime numbers,&lt;/p&gt;
&lt;p&gt;and is itself a prime number.&lt;/p&gt;
&lt;p&gt;
For example, 41 is the smallest prime number that can be expressed as
the sum of 3 consecutive primes (11 + 13 + 17 = 41) and
the sum of 6 consecutive primes (2 + 3 + 5 + 7 + 11 + 13 = 41).&lt;/p&gt;&lt;/quote&gt;
&lt;p&gt;Note that I&amp;#8217;ve got a different set of four numbers of consecutive primes than Peter&amp;#8217;s&lt;/p&gt;
&lt;h2&gt;The Approach&lt;/h2&gt;
&lt;p&gt;I always try to do &amp;#8216;the simplest thing that could possibly work.&amp;#8217;  Like Peter I had no desire to write a prime number generator.  A little googling found me the same source of prime numbers.  I figured as a first guess that the answer would probably lie somewhere within the first million prime numbers, so I downloaded &lt;a href="http://primes.utm.edu/lists/small/millions/primes1.zip"&gt;that list,&lt;/a&gt; and examined the list in Textmate.&lt;/p&gt;
&lt;p&gt;As Peter notes, the file has two lines of header, and then several primes in sequence on each line.  I just deleted the header lines in Textmate and then wrote a class which would read the file and return each prime number in sequence:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;class PrimeReader
  def initialize(file)
    @file = file
    read_line
    yield self
  end

  def next
    read_line if @numbers.empty?
    @numbers.shift.to_i
  end

  def read_line
    @numbers = @file.readline.split(' ')
  end
end&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This should be fairly explanatory. PrimeReader reads the file as necessary and hands out each prime number.&lt;/p&gt;
&lt;p&gt;Now that I had a source of consecutive primes it was time to write the code to search for the answer.  Here&amp;#8217;s the outer loop:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_ruby "&gt;&lt;span class="ident"&gt;processor&lt;/span&gt; &lt;span class="punct"&gt;=&lt;/span&gt; &lt;span class="constant"&gt;Processor&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;new&lt;/span&gt;

&lt;span class="constant"&gt;File&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;open&lt;/span&gt;&lt;span class="punct"&gt;(&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;&lt;span class="expr"&gt;#{File.dirname(__FILE__)}&lt;/span&gt;/primes1.txt&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;)&lt;/span&gt; &lt;span class="keyword"&gt;do&lt;/span&gt; &lt;span class="punct"&gt;|&lt;/span&gt;&lt;span class="ident"&gt;f&lt;/span&gt;&lt;span class="punct"&gt;|&lt;/span&gt;
  &lt;span class="constant"&gt;PrimeReader&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;new&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="ident"&gt;f&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt; &lt;span class="keyword"&gt;do&lt;/span&gt; &lt;span class="punct"&gt;|&lt;/span&gt; &lt;span class="ident"&gt;primes&lt;/span&gt; &lt;span class="punct"&gt;|&lt;/span&gt;
    &lt;span class="keyword"&gt;until&lt;/span&gt; &lt;span class="ident"&gt;processor&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;test&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="ident"&gt;primes&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;next&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt;
    &lt;span class="keyword"&gt;end&lt;/span&gt;
  &lt;span class="keyword"&gt;end&lt;/span&gt;
&lt;span class="keyword"&gt;end&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The real work is done, in the unimaginatively named Processor.  
The loop reads lines from the PrimeReader until the processor finds the desired prime or end of file generates an exception.&lt;/p&gt;
&lt;p&gt;And here&amp;#8217;s the Processor class:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;class Processor
  def initialize
    @counts = [3, 5, 275, 1167].reverse
    # @counts = [3,6]
    @sums = @counts.inject({}) { |hash, count| hash[count] = []; hash}
    @processed = []
  end

  def test(prime)
    puts &amp;quot;testing #{1+@processed.length}: #{prime} &amp;quot;
    qualifies(prime) || process(prime)
  end

  def qualifies(prime)
    @sums.each_value do | sums |
      return false unless sums.include?(prime)
    end
    report(prime)
    true
  end

  def process(prime)
    @processed &amp;lt;&amp;lt; prime
    @counts.each do |count|
      calc_sum(count)
    end
    false
  end

  def calc_sum(count)
    if @processed.length &amp;gt;= count
      @sums[count] &amp;lt;&amp;lt; @processed[-count,count].inject(0) { |sum, p| sum + p}
    end
  end

  def report(found)
    puts &amp;quot;Found #{found}&amp;quot;
    @counts.each do | count|
      report_sum(count, found)
    end
  end

  def report_sum(count, found)
    sums = @sums[count]
    sum_start = sums.index(found)
    puts &amp;quot;#{found} = #{@processed[sum_start, count].join(&amp;quot; + &amp;quot;)}&amp;quot;
  end
end&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The approach I took was to compute the sums and save them in arrays which in turn are the values for each count used as a key in the hash @sums. I keep each prime in the array @processed which is used to calculate the sums.&lt;/p&gt;
&lt;p&gt;I hard coded the parameters in the initialize method, note the commented out assignment to counts, by changing the commenting I could test the code against the example given and show that my code found 41
as the lowest prime expressible by both 3 and 6 consecutive primes.&lt;/p&gt;
&lt;p&gt;The test method reports the number and value of each prime it examines, purely as a &amp;#8216;progress indicator.&amp;#8217; The statment &amp;#8220;qualifies(prime) || process(prime)&amp;#8221; will return true if qualifies returns a truthy value, otherwise it will invoke process which always returns false.&lt;/p&gt;
&lt;p&gt;The qualifies method returns true only if the array for each count contains the current prime, which is the essence of what we are seeking. Otherwise it returns false.&lt;/p&gt;
&lt;p&gt;The process method first appends the new prime to @processed, then calculates the sum for each count using the calc_sum method.  This method determines if we have enough primes in @processed to calculate the particular sum, and if so calculates the sum and appends it to the array for the count.&lt;/p&gt;
&lt;p&gt;Once the answer has been found, the report method prints it and the sums which total to it.  The sums are calculated in the report_sum method.  This method takes a slice out of the @processed array, consisting of the count elements starting at the index where the answer is found in the particular sums array. A bit of reflection will reveal that this is precisely the primes which add to the answer.&lt;/p&gt;
&lt;p&gt;In the case of my parameters, the answer, in case you are wondering is 5,181,901, which was confirmed by Google when I gave my answer. This is the 360,245th prime number by the way.&lt;/p&gt;
&lt;h2&gt;Performance&lt;/h2&gt;
&lt;p&gt;Although this might be a bit of a brute force approach, the performance was acceptable.&lt;/p&gt;
&lt;p&gt;The biggest feature of Ruby which makes this approach feasible is the copy-on-write nature of Ruby arrays.  In Ruby Array#slice (a.k.a. Array#[]) doesn&amp;#8217;t copy the elements of the array, it just creates a new Array with an offset from the beginning of the original array and the length of the result.  As long as neither Array is changed to affect one of the shared elements, nothing is copied, but when a shared element in the source or result array is changed, Ruby first does the copy to preserve the semantics.&lt;/p&gt;
&lt;p&gt;My code does a lot of slicing of the @processed array, but other than appending to the end of the @processed array, the accesses to that array and the slices are read-only, so nothing needs to be copied.&lt;/p&gt;</description>
      <pubDate>Sat, 07 Jun 2008 21:43:00 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:df213c29-f4d4-46f4-8a4a-a8e22fc115e4</guid>
      <author>Rick DeNatale</author>
      <link>http://talklikeaduck.denhaven2.com/articles/2008/06/07/solving-the-final-google-treasure-hunt-problem-in-ruby</link>
      <category>ruby</category>
      <trackback:ping>http://talklikeaduck.denhaven2.com/articles/trackback/501</trackback:ping>
    </item>
    <item>
      <title>What Would You Miss If You Had To Stop Using Ruby and Go Back to Smalltalk?</title>
      <description>&lt;p&gt;Last night, James Robertson from Cincom, &lt;a href="http://www.cincomsmalltalk.com/blog/blogView?showComments=true&amp;#38;printTitle=Seaside_with_the_Raleigh_Rubyists&amp;#38;entry=3388818661"&gt;presented Smalltalk and Seaside to the Raleigh Ruby Brigade.&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;It was an interesting deja-vu experience, since in my younger days, part of my job with &lt;span class="caps"&gt;IBM&lt;/span&gt; was evangelizing Smalltalk, much as James does today.  It was interesting to see what has and hasn&amp;#8217;t changed. For the most part the things about Smalltalk which were blessings and curses (or many times both) haven&amp;#8217;t changed.  The &lt;span class="caps"&gt;IDE&lt;/span&gt; is still powerful. It gets much of it&amp;#8217;s power from Smalltalk&amp;#8217;s model of how source code and run-time implementation objects like compiled-methods, classes and metaclasses interact, but the consequence is that there aren&amp;#8217;t really Smalltalk source files to use with popular editors like &lt;span class="caps"&gt;VIM&lt;/span&gt; or &lt;span class="caps"&gt;EMACS&lt;/span&gt; or Textmate.  The question came up about whether the Smalltalk &lt;span class="caps"&gt;IDE&lt;/span&gt; supported the notion of giving the code to an external editor, and the answer was that the size of a typical Smalltalk method, which is the unit of editing, was so small (10 lines is a long Smalltalk method) as to make it &amp;#8216;moot.&amp;#8217;  I used to get the same kind of questions and give pretty much the same answers.&lt;/p&gt;
&lt;p&gt;One area where Smalltalk really does excel is in it&amp;#8217;s debugging and inspection tools.  The same implementation object model which enables browser features, like finding all senders or implementers of a message using structural rather than textual searching, also allows live debugging, where you can not only inspect the run-time state at a breakpoint, or when an exception occurs, but actually make changes to the running code, and compile those changes, at which point the VM prunes the invocation stack down to the point of the change and allows you to restart from that point.  Protestations from &lt;span class="caps"&gt;TDD&lt;/span&gt;/BDD adherents that &lt;a href="http://talklikeaduck.denhaven2.com/articles/2007/10/18/true-confesssions"&gt;you don&amp;#8217;t need no steenking debugger&lt;/a&gt; if you follow &lt;span class="caps"&gt;TDD&lt;/span&gt; practice, the Smalltalk debugger was tool much favored by the very people, like Kent Beck, who invented &lt;span class="caps"&gt;TDD&lt;/span&gt;.  Many Rubyists who were around for more than a year or two had an anti-debugger attitude, generated more, I suspect, by the lack of a decent Ruby debugger than any real hatred of debuggers.&lt;/p&gt;
&lt;p&gt;Now that ruby-debug has been around for &lt;a href="http://datanoise.com/articles/2006/7/7/faster-debugger-for-ruby"&gt;almost two years&lt;/a&gt;, the situation is much better. Ruby has a fairly competent debugger which allows stepping through code.  It&amp;#8217;s still hampered by Ruby&amp;#8217;s rather simple run-time meta information, being forced to work on a line-by-line mode, rather than being able to step through individual expressions as can the Smalltalk debugger.  And we&amp;#8217;re still a long way from the live surgery capabilities I described. Perhaps as Ruby VM implementations mature we might see some of these advanced features emerge, perhaps this is something which the Rubinius implementers might also take as an inspiration from Smalltalk.  This is one of the main things I miss from my Smalltalk days.&lt;/p&gt;
&lt;p&gt;On the other hand, at this point in time, I&amp;#8217;m really much happier working in Ruby than  I think I would be were I somehow forced to work in Smalltalk again instead.  Much as I love it, Smalltalk is now my second favorite language.&lt;/p&gt;
&lt;p&gt;At one point last night, Brian Adkins asked me the question which is the title of this article.  I think it&amp;#8217;s a fair question, and I&amp;#8217;m not sure I know exactly, but let me try to answer it.&lt;/p&gt;
&lt;h2&gt;What I&amp;#8217;d miss from Ruby&lt;/h2&gt;
&lt;p&gt;I&amp;#8217;ve said this before, but one of the things I like about Ruby is that it is more dynamic than Smalltalk in ways which I like, and cuts back on other aspects of Smalltalk which I don&amp;#8217;t think are really that important.&lt;/p&gt;
&lt;p&gt;One of the things I like about Ruby is the &lt;a href="http://talklikeaduck.denhaven2.com/articles/2008/02/08/whose-variable-is-it-anyway"&gt;elimination of variable declarations.&lt;/a&gt; A good example of this was that during the Seaside demo last night, James showed how interfacing to the database requires attribute instance variables in model objects to be declared.  Now the &lt;span class="caps"&gt;IDE&lt;/span&gt; provides tools for helping with this, you get prompted with a list of column names and can add them one by one just by clicking buttons.  Contrast this with ActiveRecord where model objects just acquire instance variables dynamically at run-time.  Now I know that some prefer more explicit mappings, but personally I feel that the dynamic mapping provides much more capability for much less ceremony.&lt;/p&gt;
&lt;p&gt;The ways in which Ruby is more dynamic than Smalltalk seem to me to provide better facilities for building low-ceremony architectures and artifacts like Rails, Rake, etc.  There are more dynamic languages than Ruby to be sure, such as Self, and from what I can sense JavaScript, but Ruby seems to strike a very nice balance.&lt;/p&gt;
&lt;p&gt;Much has been made of the legacy of Smalltalk in pioneering metaprogramming, although some Lisp guys might quibble with that, and in truth, most Smalltalk metaprogramming was only used to support the &lt;span class="caps"&gt;IDE&lt;/span&gt; and never put to use by application programmers.  Alan Kay used to say that he was disappointed that no one seemed to make new classes of Behavior (which is the superclass of both Class and Metaclass in Smalltalk). I know he said this to some of us at an &lt;span class="caps"&gt;IBM&lt;/span&gt; internal conference, which at least led to Dave Smith and Jerry Archbald developing a &amp;#8220;behavior of behavior&amp;#8221; tutorial which ran for several years at &lt;span class="caps"&gt;OOPSLA&lt;/span&gt;.  But Rubyists have taken metaprogramming much further than I recall from my Smalltalk days.&lt;/p&gt;
&lt;p&gt;On the other end of the scale, Smalltalk as James pointed out, as I used to, has a very simple syntax, a few reserved words (self, super, nil, true, and false), three types of messages (unary, binary, and keyword),  two operators (:= for assignment, and &amp;#94; for return), and a few more things for defining block literals.&lt;/p&gt;
&lt;p&gt;Now when I was doing James&amp;#8217; job, this got mixed reactions. Some people took to syntax like:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_smalltalk "&gt;topLeft = Point x: 3+2*5 y: 15&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;While others found it just a little too strange, something which we Smalltalkers just couldn&amp;#8217;t get.&lt;/p&gt;
&lt;p&gt;Another thing which put off newcomers to Smalltalk was that, because of the simplicity of the language, and the lack of any form of operator precedence (remember the only operators are := and &amp;#94;), that subexpression 3+2*5 evaluates to 25 and not 13.&lt;/p&gt;
&lt;p&gt;Ruby trades off a little simplicity and does provide precedence between messages which seem like they should act as operators.&lt;/p&gt;
&lt;p&gt;I&amp;#8217;m not saying that Ruby is without quirks, just that different people react to different quirks in different ways.  If you don&amp;#8217;t like what you perceive to be the quirks of &lt;strong&gt;any&lt;/strong&gt; programming language, you won&amp;#8217;t be convinced, even by the most ardent supporter of those quirks.&lt;/p&gt;
&lt;p&gt;One of the interesting effects of the Smalltalk syntax was that, as we observed back in Smalltalk&amp;#8217;s heyday in the Enterprise (late &amp;#8216;80s-early &amp;#8216;90s), it seemed that a lot of &lt;span class="caps"&gt;COBOL&lt;/span&gt; programmers seemed to take to Smalltalk. We used to think that Smalltalk might actually become the 21st century &lt;span class="caps"&gt;COBOL&lt;/span&gt;, until the &amp;#8220;Enterprise&amp;#8221; got wooed away by EJBs and the like. The same things which made Smalltalk approachable by &lt;span class="caps"&gt;COBOL&lt;/span&gt; programmers made it seem weird to those who looked down on those &lt;span class="caps"&gt;COBOL&lt;/span&gt; programmers as &amp;#8220;trade-school&amp;#8221; programmers.&lt;/p&gt;
&lt;p&gt;Another much-touted feature of Smalltalk, is that everything is done by message sending, even control flow.  In Smalltalk a if/then/else control flow is achieved by sending an ifTrue:ifFalse: message to a boolean object as in:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_smalltalk "&gt; ^(x = 0) ifTrue:[a] ifFalse:[b]&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Smalltalk evaluates this as if the the expression (x = 0) is evaluated by sending the message with the selector = and argument 0, to the object referenced by x.  The result of that message, an object of course, is then sent the message with the selector ifTrue:ifFalse: and the arguments [a] and [b], which are two blocks.  What happens is up to that object.  Typically that object is either true (the sole instance of the class True) whose ifTrue:ifFalse: method evaluates the first argument, or false (the sole instance of the class False) whose ifTrue:ifFalse: method evaluates the second argument.  Very neat and conceptually clean.  It allows you to define your own control flow methods.&lt;/p&gt;
&lt;p&gt;Ruby on the other hand compiles if statements and their kind as tests and branches, much as a C compiler would.  We trade off a little flexibility for performance.&lt;/p&gt;
&lt;p&gt;But, in my experience, that flexibility rarely got used in Smalltalk.  Not only that but, in my day at least, the Smalltalk compilers would &lt;strong&gt;also&lt;/strong&gt; compile ifTrue:ifFalse: to a test of the result of the &amp;#8216;receiver&amp;#8217; and a branch.  In fact I just tried defining a FakeBoolean class with an ifTrue: method and when I try to use it I see this:&lt;/p&gt;
&lt;img src="http://talklikeaduck.denhaven2.com/files/2008-05-21_must_be_boolean.png" alt="must_be_boolean" height="326" width="326"&gt;
&lt;p&gt;That NonBooleanReceiver exception is like seeing the Wizard of Oz behind the curtain, this notion of no control flow, just messages is actually a bit of an illusion.&lt;/p&gt;
&lt;p&gt;Again, while Ruby doesn&amp;#8217;t even pretend to implement all control flow by messaging, it provides most of what the underlying Smalltalk mechanisms are really used for in the form of blocks used to implement iterators.&lt;/p&gt;
&lt;p&gt;There are other aspects of Smalltalk which are both blessings and curses.  The fact that Smalltalk has a persistent run-time image, containing all the development tools, which can be saved along with its state of execution, and restarted is quite powerful, alien to many programmers, and can drastically change your approach to deployment.  Back when I was doing Smalltalk we always struggled with issues like the footprint of the image, how to strip out the development tools before deployment, and start-up time.  Some of these problems might seem to be less severe with today&amp;#8217;s hardware, but they are still issues.&lt;/p&gt;
&lt;p&gt;I feel that I might be coming across a little too harshly on my old friend Smalltalk.  It still provides a great programming environment, and serves as a source of inspiration which shouldn&amp;#8217;t be overlooked, and I hope to see some of the powerful development tool features from Smalltalk appear with help from support in some of the emerging Ruby implementations.  I&amp;#8217;m glad to see that it seems to be making somewhat of a resurgence, along with dynamic languages in general.  But for me right now, while I wouldn&amp;#8217;t be unhappy if I had to go back to Smalltalk, but I feel happier with Ruby.&lt;/p&gt;</description>
      <pubDate>Wed, 21 May 2008 16:58:00 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:8d57cff0-8bf8-43fe-8b97-c7b98decd8f1</guid>
      <author>Rick DeNatale</author>
      <link>http://talklikeaduck.denhaven2.com/articles/2008/05/21/what-would-you-miss-if-you-had-to-stop-using-ruby-and-go-back-to-smalltalk</link>
      <category>ruby</category>
      <category>war_stories</category>
      <category>smalltalk</category>
      <category>seaside</category>
      <category>debugging</category>
      <trackback:ping>http://talklikeaduck.denhaven2.com/articles/trackback/500</trackback:ping>
    </item>
    <item>
      <title>On Ceremony and Training Wheels</title>
      <description>&lt;p&gt;The perennial topic of &lt;a href="http://www.nabble.com/Not-quite-getting-it.-td17281703.html"&gt;&lt;strong&gt;getting&lt;/strong&gt; duck-typing in ruby&lt;/a&gt; has come up again.  A ruby nuby wonders about the dangers of passing a &amp;#8220;giraffe&amp;#8221; object to a method expecting an &amp;#8220;order.&amp;#8221; Or asking an object to &amp;#8220;draw&amp;#8221;, expecting it to be a &amp;#8220;brush&amp;#8221; when it was really a &amp;#8220;cowboy.&amp;#8221;&lt;/p&gt;
&lt;p&gt;These are reasonable questions, coming from someone who is used to a high-ceremony language which gives at least the illusion of protection from such &amp;#8220;errors.&amp;#8221;  Note that method signatures in languages like Java can&amp;#8217;t really protect from a draw method doing different things in different classes.&lt;/p&gt;
&lt;p&gt;J. Cooper offered the following good advice:&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;Instead, look at it like this: how likely is a Giraffe able to do what
an Order does? If the Giraffe doesn&amp;#8217;t quack like an Order, than an
exception is going to be thrown automatically anyway.&lt;/p&gt;
&lt;p&gt;Just program in it, and see how often it ever actually bites you. Start
with small things, work your way up.&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;The advice here is to tackle the problem of learning a language like Ruby with a certain amount of fearlessness.  This reminds me of learning to ride a bike.&lt;/p&gt;
&lt;p&gt;The traditional way of learning to ride a bicycle is to use training wheels, sometimes even progressively.  Your dad might have installed the training wheels so that they touched the ground, turning the bike into a kind of tricycle with an extra, overly large back wheel between the normal ones.  You think you&amp;#8217;re riding a bike, but you&amp;#8217;re really still on a trike.&lt;/p&gt;
&lt;p&gt;The next stage, is for dad to raise the training wheels a bit so that you need to start learning to balance properly, but you can&amp;#8217;t really tip too far. Now you&amp;#8217;re riding something that kind of acts like a bicycle, but which &amp;#8220;flops over&amp;#8221; into tricycle mode.&lt;/p&gt;
&lt;p&gt;If you never get past this stage, you never really learn to ride a bike.  In an analogy with programming in Ruby, training wheels are &lt;a href="http://talklikeaduck.denhaven2.com/articles/2007/10/22/chicken-typing-isnt-duck-typing"&gt;chicken typing&lt;/a&gt; devices.&lt;/p&gt;
&lt;p&gt;The truth is that bicycles and motorcycles operate quite differently than wheeled vehicles which keep three or more wheels on the ground, for one thing you steer by leaning, not with the handlebars or steering wheel.  Learning to fly an airplane gives even stronger examples of having to learn that your instincts are wrong, and that you have to train yourself to &amp;#8220;instinctively&amp;#8221; know not only that you turn by banking rather than with the rudder, but that you control altitude primarily with the throttle, not the elevators, speed primarily with the elevators not the throttle, and so forth.&lt;/p&gt;
&lt;p&gt;Now the use of training wheels, or flight simulators, might be considered a ceremony, although a necessary rite of passage for many learners.  Given the high cost of mistakes in learning, it&amp;#8217;s no doubt a good thing that student pilots get time in simulators and in dual control planes accompanied by a flight instructor before soloing.  Although the way most young birds learn to fly is to be throw out of the nest to &amp;#8220;sink&amp;#8221; or &amp;#8220;swim&amp;#8221; so to speak.&lt;/p&gt;
&lt;p&gt;In learning to program, it&amp;#8217;s hard to see a difference between a simulator and reality, so it&amp;#8217;s perfectly feasible to &amp;#8220;fly the plane&amp;#8221; from the start. The consequences of a mistake are no more dire than making a mistake in a flight simulator.  It&amp;#8217;s really just a matter of conquering fear, not to rely on chicken-typing, and the more mistakes you make and correct, the more quickly you come to grips with the differences in really using a dynamically typed language from earlier experiences.&lt;/p&gt;
&lt;p&gt;Some can do this easier than others.  For example, Alex, my 6-year old next-door neighbor recently jumped off his tricycle, and onto a bicycle (sans training wheels) and is now zooming around our cul-de-sac faster than ever before.&lt;/p&gt;
&lt;p&gt;So if you&amp;#8217;re struggling with how to program Ruby or a similar language because lacking ceremonial training wheels to &amp;#8220;bridge the gap&amp;#8221; from Java or a similar language.  Might I suggest that you just jump in like Alex and give it a whirl.&lt;/p&gt;
&lt;p&gt;Of course, it&amp;#8217;s rarely easy to be as fearless as a 6-year old!&lt;/p&gt;</description>
      <pubDate>Sun, 18 May 2008 10:15:00 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:d174206d-505d-465b-8cbd-435bd179a143</guid>
      <author>Rick DeNatale</author>
      <link>http://talklikeaduck.denhaven2.com/articles/2008/05/18/on-ceremony-and-training-wheels</link>
      <category>ruby</category>
      <category>ducks</category>
      <category>chickens</category>
      <category>ceremony</category>
      <trackback:ping>http://talklikeaduck.denhaven2.com/articles/trackback/499</trackback:ping>
    </item>
    <item>
      <title>The Perils of Ruby</title>
      <description>Charlie Nutter just published an article which assesses &lt;a href="http://headius.blogspot.com/2008/04/promise-and-peril-for-alternative-ruby.html"&gt;the various implementations of Ruby&lt;/a&gt;. In all it&amp;#8217;s a quite even-handed description coming from one of the main proponents of JRuby.
&lt;p&gt;Charlie talks about each implementation and describes the perils each faces.&lt;/p&gt;
&lt;p&gt;These seem to be days of crisis for Ruby.  With so many implementations compatibility is a challenge.  Particularly since Ruby lacks a formal specification.  The Rubinius developers have been working hard to address this by developing, RubySpecs, a set of &lt;a href="http://rubinius.lighthouseapp.com/projects/5089/specs-overview"&gt;rspec style specifications for Ruby&lt;/a&gt;.  Matz has also convened a regular meeting of Ruby implementors via irc.  The &lt;a href="http://ruby-design.pbwiki.com/Design20080421"&gt;first meeting took place last week,&lt;/a&gt;and one of the decisions taken was to make RubySpec the officially blessed set of tests to be used by all implementors.&lt;/p&gt;
&lt;blockquote class="pullquote"&gt;Compatibility is &lt;strong&gt;hard&lt;/strong&gt;. I&amp;#8217;m not talking a little hard, I&amp;#8217;m talking monumentally hard. Ruby is a very flexible, complicated language to implement, and it ships with a number of very flexible, complicated core class implementations. Very little exists in the way of specifications and test kits. &amp;#8211; Charles Nutter&lt;/blockquote&gt;
&lt;h2&gt;Is Ruby Forking?&lt;/h2&gt;
&lt;p&gt;Currently there are two major &amp;#8220;official&amp;#8221; versions of Ruby. Ruby 1.8, which is in use for most production purposes, and Ruby 1.9 which introduces new features (e.g. integrated support for strings with different encodings), new language features (e.g. new syntax for hash literals which allows actual parameters to methods taking an options hash as the last argument to look like keyword parameters), and some incompatibilities.&lt;/p&gt;
&lt;p&gt;As Charlie points out the peril here is that Rubyists have a hard time figuring out which Ruby to target.  Ruby 1.9 isn&amp;#8217;t yet ready for production, but even when it is, will the advantages outweigh the cost of the &amp;#8216;porting&amp;#8217; needed to get past the incompatibilities.&lt;/p&gt;
&lt;p&gt;Some implementations are attempting to bridge the gap. JRuby is taking on some 1.9 features while maintaining compatibility with 1.8.  The recent preview release of Ruby 1.8.7, also introduces some 1.9 features to the 1.8.x code base, albeit with some initial incompatibilities, which hopefully will be worked out. RubySpec should help this.&lt;/p&gt;
&lt;p&gt;MacRuby, on the other hand, is taking another approach to 1.9 features.  MacRuby is a new Apple implementation of Ruby which uses the Objective-C run-time as a platform, much as JRUby and IronRuby use the Java &lt;span class="caps"&gt;JVM&lt;/span&gt;, and Microsoft &lt;span class="caps"&gt;DLR&lt;/span&gt;, as platforms.&lt;/p&gt;
&lt;p&gt;One of the ways in which MacRuby exploits 1.9 is the way they are mapping the new hash literal syntax I just mentioned.  Let&amp;#8217;s look a bit at that new syntax.&lt;/p&gt;
&lt;p&gt;At the risk of offending the &amp;#8220;Rails isn&amp;#8217;t Ruby crowd&amp;#8221;, I&amp;#8217;m going to take an example from ActiveRecord, because Rails tends to use option hash parameters quite a bit.  In Ruby 1.8 I might code:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;Book.find(:all, :order =&amp;gt; &amp;quot;title ASC&amp;quot;, :limit =&amp;gt; 10)&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;To get the first 10 books sorted by title.  The new Ruby 1.9 syntax allows this to be written alternatively as:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_ruby "&gt;&lt;span class="constant"&gt;Book&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;find&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="symbol"&gt;:all&lt;/span&gt;&lt;span class="punct"&gt;,&lt;/span&gt; &lt;span class="ident"&gt;order&lt;/span&gt;&lt;span class="punct"&gt;:&lt;/span&gt; &lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;title ASC&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;,&lt;/span&gt; &lt;span class="ident"&gt;limit&lt;/span&gt;&lt;span class="punct"&gt;:&lt;/span&gt; &lt;span class="number"&gt;10&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Which is actually an identical call.  These &amp;#8220;keyword arguments&amp;#8221; are quite reminiscent of the Smalltalk-inspired syntax used in Objective-C. As I understand it, MacRuby will look at such a call, and turn it into an Objective-C message internally something like:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_objective-c "&gt;[Book find: @selector(all) order: &amp;quot;title ASC&amp;quot; limit: 10]&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;But this isn&amp;#8217;t exactly the same.  In Ruby one method can handle multiple optional keyword arguments which can appear (or not) in any order.  In Objective-C the message selectors find:order:limit, and find:limit:order would map to different methods.  When I asked Laurent Sansonetti about this on ruby-core, he said that the implementation would actually determine whether the receiving object understands :find:order:limit: and if not fall back to a more ruby-like call.  I&amp;#8217;m not sure how such a chicken-typed implementation will really stand up in practice, but I guess that time will tell.&lt;/p&gt;
&lt;p&gt;I&amp;#8217;m also not sure what the long-term implications of this are as Matz moves from 1.9 to 2.0 and perhaps starts defining new method definition syntax which provides syntactic sugar (at least) for handling &amp;#8220;keyword parameter&amp;#8221; hashes on the other side of the  invocation.&lt;/p&gt;
&lt;h2&gt;Platforms, Platforms, Platforms&lt;/h2&gt;
&lt;p&gt;As I said above, one way to characterize the various ruby implementations is by the platform each &amp;#8216;advocates&amp;#8217;.  Traditional &lt;span class="caps"&gt;MRI&lt;/span&gt; Ruby, and Ruby 1.9 run well on &lt;span class="caps"&gt;UNIX&lt;/span&gt; like platforms like Linux, &lt;span class="caps"&gt;OS X&lt;/span&gt;, and Solaris. Rubinius is building a new Ruby-based platform using ideas from Squeak and earlier Smalltalk implementations, although as far as I can tell, it&amp;#8217;s not following the Smalltalk philosophy of being an &amp;#8220;operating system&amp;#8221; on its own, IronRuby is really an attempt to optimize a Ruby implementation for Microsoft Platforms, while JRuby leverages the &lt;span class="caps"&gt;JVM&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;I can&amp;#8217;t help but think back to the early 1990s as a member of the Smalltalk community.  Smallalk had gained a fair bit of traction in the enterprise, particularly in industries such as finance and insurance where rapid application development was important. Java started to take the wind out of Smalltalk&amp;#8217;s sails.  I always considered the switch from Smalltalk to Java to be driven by factors such as the cost of entry for an individual programmer, but my old friend Dave Thomas (OTI&amp;#8217;s BigDave, not pragDave) points out that it was more a matter of companies like &lt;span class="caps"&gt;IBM&lt;/span&gt; (one of the main Smalltalk vendors by then) moving to Java as an anti-Microsoft platform. Java really took off in the enterprise after &lt;span class="caps"&gt;IBM&lt;/span&gt;, Sun, and others entered a kind of &lt;span class="caps"&gt;ABM&lt;/span&gt; treaty (Anyone But Microsoft)&lt;/p&gt;
&lt;p&gt;Ruby is in a different place than Smalltalk was at that time. Smalltalk was available from, and advocated by, a small number of vendors who sold it at a handsome price.  Two of the big Smalltalk implementations survive, &lt;span class="caps"&gt;IBM&lt;/span&gt;/VisualAge Smalltalk is still available from Instantiations &lt;a href="http://www.instantiations.com/VAST/purchase.html"&gt;at a four figure price&lt;/a&gt;. Cincom sells the latest version of VisualWorks Smalltalk, under a complex web of licensing options. Both of these &amp;#8220;compete&amp;#8221; with the open-source Squeak implementation.&lt;/p&gt;
&lt;p&gt;The environment has shifted out from under the big corporate providers of software development tooling like &lt;span class="caps"&gt;IBM&lt;/span&gt;, Sun and Microsoft. It&amp;#8217;s hard to see how to make big bucks selling development tools when so much is available under various open-source licenses for the cost of a download.&lt;/p&gt;
&lt;p&gt;Ruby has come out of today&amp;#8217;s open-software environment. It was conceived out of one man&amp;#8217;s desire for a language which he personally found pleasing, and grew within the open source community.  While I applaud and appreciate the support that Ruby has received from Sun, Microsoft, Apple, and other corporations, I can&amp;#8217;t help but feeling that some of the motivation is based on keeping control of the platform.&lt;/p&gt;
&lt;p&gt;These might be perilous times for Ruby, but I&amp;#8217;ve got confidence that the overall community will keep things from getting too far out of whack.&lt;/p&gt;
&lt;p&gt;Again, time will tell.&lt;/p&gt;</description>
      <pubDate>Sun, 27 Apr 2008 15:17:00 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:74c1c878-8e63-4058-a787-d9af613f2af7</guid>
      <author>Rick DeNatale</author>
      <link>http://talklikeaduck.denhaven2.com/articles/2008/04/27/the-perils-of-ruby</link>
      <category>ruby</category>
      <category>opinion</category>
      <trackback:ping>http://talklikeaduck.denhaven2.com/articles/trackback/496</trackback:ping>
    </item>
    <item>
      <title>x ||= y, Redux</title>
      <description>A while back there was quite a thread on the Ruby-lang mailing list about the real semantics of the expression.
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;a[x] ||= some_value&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;In many books and articles on Ruby the form:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;a &amp;lt;op&amp;gt;= b&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Where &amp;LT;op&amp;GT; is an operator like + Is described as syntactic sugar:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;a = a &amp;lt;op&amp;gt; b&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;While this is true in most cases, it &lt;strong&gt;isn&amp;#8217;t&amp;#8217;&lt;/strong&gt; true if the operator is ||.&lt;/p&gt;
&lt;p&gt;This comes to light when the left hand side is a method call, to an accessor, or accessor-like method. For example&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;h = Hash.new(&amp;quot;hello&amp;quot;)
h[:fred] ||= &amp;quot;&amp;quot;
h #=&amp;gt; {}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Some find it surprising that the assignment doesn&amp;#8217;t cause the hash to have :fred as a key. What this code snippet shows is that the assignment doesn&amp;#8217;t actually assign anything if the left hand expression returns a logically true value.  A Hash with a default value will return the default value when accessed by any key which is not present in the hash.  Since h[:fred] returns the default value, the assignment doesn&amp;#8217;t happen.&lt;/p&gt;
&lt;p&gt;This affects any object which has &amp;#8216;accessor&amp;#8217; methods. Here&amp;#8217;s a class cooked up just to explore this aspect of Ruby.&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;class ChattyCathy

  def initialize(x=nil)
    @x = x
    puts &amp;quot;created x is now #{x.inspect}&amp;quot;
  end

  def x
    puts &amp;quot;x read x is #{@x.inspect}&amp;quot;
    @x
  end

  def x=(val)
    puts &amp;quot;x written, now #{val.inspect}&amp;quot;
    @x = val
  end
end&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The purpose of this class is simply to let us see exactly when the x attribute is read and written. Now if we run this code&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;c = ChattyCathy.new(42)
puts &amp;quot;about to evaluate c.x ||= 43&amp;quot;
c.x ||= 43
c = ChattyCathy.new
puts &amp;quot;about to evaluate c.x ||= 43&amp;quot;
c.x ||= 43&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;We get the following output:&lt;/p&gt;
&lt;xmp&gt;
    created x is now 42
    about to evaluate c.x ||= 43
    x read x is 42
    created x is now nil
    about to evaluate c.x ||= 43
    x read x is nil
    x written, now 43
&lt;/xmp&gt;
&lt;p&gt;Which clearly illustrates just when the assignment actually happens.&lt;/p&gt;
&lt;h2&gt;The real expansion of x ||= y&lt;/h2&gt;
&lt;p&gt;Matz explains that the real expansion of x ||= y is:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;x || x = y&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The expectation that x ||= y is the same as x = x || y, does seem reasonable to someone &amp;#8216;coming from&amp;#8217; C or one of it&amp;#8217;s derivative languages.  As far as I can determine, C introduced the notion of assignment operators like += and -=.  And K&amp;#38;R defined these assignment operators as a shorthand for x = x + y, etc.&lt;/p&gt;
&lt;p&gt;On the other hand, although C has logical operators || and &amp;#38;&amp;#38; which, like Ruby have &amp;#8216;short-circuit&amp;#8217; evaluation, it doesn&amp;#8217;t allow ||=, or &amp;#38;&amp;#38;= as assignment operators.&lt;/p&gt;&lt;p&gt;Since || is a &amp;#8216;short-circuit&amp;#8217; boolean operator, the left hand operand expression is only evaluated if the right hand operand expression evaluates to a logically false value, i.e. either nil or false.&lt;/p&gt;
&lt;p&gt;The way that Matz included ||= as an assignment operator makes perfect sense to me. The ||= assignment operator reserves the short-circuit nature of ||.&lt;/p&gt;
&lt;h2&gt;So what about x &amp;#38;&amp;#38;= y&lt;/h2&gt;
&lt;p&gt;Although I haven&amp;#8217;t seen this discussed anywhere, &amp;#38;&amp;#38;= in Ruby has similar behavior:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;c = ChattyCathy.new
puts &amp;quot;about to evaluate c.x &amp;amp;&amp;amp;= true&amp;quot;
c.x &amp;amp;&amp;amp;= true
puts &amp;quot;about to evaluate c.x = \&amp;quot;hi\&amp;quot;&amp;quot;
c.x = &amp;quot;Hi&amp;quot;
puts &amp;quot;about to evaluate c.x &amp;amp;&amp;amp;= true&amp;quot;
c.x &amp;amp;&amp;amp;= true&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;xmp&gt;
    created x is now nil
    about to evaluate c.x &amp;#38;&amp;#38;= true
    x read x is nil
    about to evaluate c.x = &amp;#8220;hi&amp;#8221; 
    x written, now &amp;#8220;Hi&amp;#8221; 
    about to evaluate c.x &amp;#38;&amp;#38;= true
    x read x is &amp;#8220;Hi&amp;#8221; 
    x written, now true
&lt;/xmp&gt;
&lt;p&gt;So the expansion of x &amp;#38;&amp;#38;= y is x &amp;#38;&amp;#38; x = y&lt;/p&gt;</description>
      <pubDate>Sat, 26 Apr 2008 11:11:00 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:ecdb3ccb-c373-4025-8709-3f5ad3ddb52c</guid>
      <author>Rick DeNatale</author>
      <link>http://talklikeaduck.denhaven2.com/articles/2008/04/26/x-y-redux</link>
      <category>ruby</category>
      <trackback:ping>http://talklikeaduck.denhaven2.com/articles/trackback/495</trackback:ping>
    </item>
    <item>
      <title>Best Practice Patterns, Accessors and Encapsulation</title>
      <description>&lt;p&gt;&lt;img src="http://talklikeaduck.denhaven2.com/files/2008-02-15_kents_autograph_to_me_on_stbpp.png" alt="Kent's Autograph to me on STBPP" height="255" width="250" class="tease-image"&gt;
One of the classics in the Smalltalk literature, which  has also had a big influence on the Ruby community is Kent Beck&amp;#8217;s &lt;a href="http://www.amazon.com/gp/product/013476904X?ie=UTF8&amp;#38;tag=denhaven2com-20&amp;#38;linkCode=as2&amp;#38;camp=1789&amp;#38;creative=9325&amp;#38;creativeASIN=013476904X"&gt;&amp;#8220;Smalltalk Best Practice Patterns&amp;#8221;&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=denhaven2com-20&amp;#38;l=as2&amp;#38;o=1&amp;#38;a=013476904X" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;, which captures the best practices for designing and coding Smalltalk programs.  Back when it was published, I used to see Kent a few times a year, and happened to be in the Bay area when he made an author appearance at the Computer Literacy Bookstore in San Jose, where I got my copy, and the autograph shown here.
&lt;p&gt;The Ruby language has many similarities with Smalltalk, so much of Kent&amp;#8217;s advice applies to Ruby.  I frequently hear prominent Rubyists mention the book.&lt;/p&gt;
&lt;p&gt;On the other hand, Ruby is not exactly Smalltalk, so Kent&amp;#8217;s book isn&amp;#8217;t an exact fit to Ruby. I&amp;#8217;ve been wanting to start writing about adapting some of these patterns to Ruby for a while, so this article will hopefully be the first in a series.&lt;/p&gt;
&lt;h2&gt;The Motivation For This Article&lt;/h2&gt;
&lt;p&gt;Recently on the ruby-talk forum a thread discussing &lt;a href="http://www.ruby-forum.com/topic/141107"&gt;accessor methods vs. direct instance variable access&lt;/a&gt; came up.  This was a hot debate topic in the Smalltalk community back in the 90s, and Kent addressed it in two competing patterns in the book, one of which Ryan Davis (a.k.a ZenSpider) brought up in the conversation.&lt;/p&gt;&lt;/p&gt;


&lt;h2&gt;Patterns Are Decisions, Not Prescriptions.&lt;/h2&gt;
&lt;p&gt;In their best form, patterns represent a network of decisions made during the creation of something, in this case software.  A good pattern should describe the &lt;strong&gt;forces&lt;/strong&gt; which affect the decision whether or not to adopt the particular &lt;strong&gt;solution&lt;/strong&gt; it offers.&lt;/p&gt;
&lt;p&gt;There can often be a tension between competing patterns, different patterns optimize different desirable characteristics, such as readability vs. flexibility.&lt;/p&gt;
&lt;p&gt;The forces, or their relative strength, can be affected by technical factors such as the language, and features of the editor or &lt;span class="caps"&gt;IDE&lt;/span&gt; being used. To varying degrees many or all of Kent&amp;#8217;s Smalltalk patterns have forces affected by the capabilities of the Smalltalk &lt;span class="caps"&gt;IDE&lt;/span&gt;. One of Kent&amp;#8217;s main goals is readable code, so writing code to maximize the utility of the code exploration features of the Smalltalk browsers, inspectors, and debugger figures into the book.&lt;/p&gt;
&lt;h2&gt;A Tale of Two Patterns&lt;/h2&gt;
&lt;p&gt;Now to the specifics of the article at hand.  The book has two patterns described in sequence,starting on page 89, &amp;#8220;Direct Variable Access&amp;#8221;, and &amp;#8220;Indirect Variable Access&amp;#8221;. Both address the same problem &amp;#8220;How do you get and set an instance variable&amp;#8217;s value?&amp;#8221; and give two opposing solutions, along with a good discussion of the tensions.&lt;/p&gt;
&lt;p&gt;The first pattern, as the name implies, advocates referring to an instance variable directly by name, so in Ruby, within a method, you&amp;#8217;d just write @x, instead of using accessor methods, the second pattern.&lt;/p&gt;
&lt;p&gt;As Kent points out in the discussion of the first pattern, direct vs. indirect access was a hotly debated topic in the Smalltalk community, although indirect access got to be popular since it was advocated by several Smalltalk training companies.&lt;/p&gt;
&lt;h2&gt;Tension Number One: Readability&lt;/h2&gt;
&lt;p&gt;In his argument for direct variable access, Kent explains that whenever he ran into an accessor method invocation, which in Smalltalk looks like this:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_Smalltalk "&gt;a = self x&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;He found himself pausing to remind himself that x was &amp;#8220;just&amp;#8221; accessing an instance variable, but that he would read the direct form:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_Smalltalk "&gt;a = x&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;without breaking his stride.&lt;/p&gt;
&lt;p&gt;I might point out that Ruby is subtly different here. First, direct instance variable access is clearly marked with the &amp;#8221;@&amp;#8221; sigil.  On the other hand, a read accessor invocation in Ruby can be written without the explicit self receiver:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_ruby "&gt;&lt;span class="ident"&gt;a&lt;/span&gt; &lt;span class="punct"&gt;=&lt;/span&gt; &lt;span class="ident"&gt;x&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;So it&amp;#8217;s not as clear that this is a method invocation as opposed to a local variable access, although we know that it &lt;strong&gt;isn&amp;#8217;t&lt;/strong&gt; a direct instance variable access. Write accessor invocation usually requires an explicit receiver:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_ruby "&gt;&lt;span class="constant"&gt;self&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;x&lt;/span&gt; &lt;span class="punct"&gt;=&lt;/span&gt; &lt;span class="ident"&gt;a&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;to disambiguate between a write accessor call and simply assigning to a local variable, at least the first time x appears in a particular lexical scope.&lt;/p&gt;
&lt;h2&gt;Tension Number Two: Subclassablity&lt;/h2&gt;
&lt;p&gt;Although direct instance variable is more readable, it does have a drawback in that it makes certain subclassing patterns harder to implement.&lt;/p&gt;
&lt;p&gt;If a class uses indirect variable access consistently, then a subclass can leverage this by overriding the accessor.  For example, lets say we want a subclass which audits changes to an instance variable.  By overriding the setter accessor it can do things like logging changes very simply.  Otherwise any methods which access the instance variable in the superclass need to be overridden.&lt;/p&gt;
&lt;p&gt;Kent&amp;#8217;s example is defining a PolarPoint subclass of Point which has radius and theta instance variables, and overrides Point&amp;#8217;s accessors for x and y.  One interesting aspect of the Ruby/Smalltalk comparison when you look at this example a little more deeply relates to my recent article about instance variables.  In Smalltalk since the Point class has x and y instance variables, it&amp;#8217;s subclass PolarPoint would have x, y, radius and theta instance variables, although the x and y variables would be vestigial and unused.  In Ruby a PolarPoint instance wouldn&amp;#8217;t acquire the unneeded x and y instance variables.&lt;/p&gt;
&lt;h2&gt;The Encapsulation Tension&lt;/h2&gt;
&lt;p&gt;One of the reasons why there was/is such a debate between proponents of direct vs. indirect instance variable access is the effect providing setter and getter accessors has on the apparent encapsulation of the object&amp;#8217;s state.&lt;/p&gt;
&lt;p&gt;First, in either Ruby or Smalltalk, the mere absence of accessor methods doesn&amp;#8217;t prevent encapsulation intrusions.  Ruby has the instance_variable_get and instance_variable_set methods, and Smalltalk has instVarAt: and instVarAt:put:, but these methods are &amp;#8216;marked&amp;#8217; as slightly evil and reserved for dastardly deeds.&lt;/p&gt;
&lt;p&gt;An accessor method on the other hand seems much more like any other normal method.  In Smalltalk, convention is used to mark methods as private, although this is very weak consisting simply of putting private methods in a particular category in the browser, with no runtime check.  Ruby does provide runtime checking of both private and protected methods, although even this protection can be circumvented, using &lt;strong&gt;send&lt;/strong&gt;.&lt;/p&gt;
&lt;H2&gt;Summing Up&lt;/H2&gt;
&lt;p&gt;So in the end, the existence of and the tension between these two patterns demonstrates some key points:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Patterns present choices, and the best patterns provide enough information to make an informed decision on a case-by-case basis.&lt;/li&gt;
&lt;li&gt;The languages and the tools we use have an effect on the patterns and the decisions they engender.&lt;/li&gt;&lt;/ul&gt;</description>
      <pubDate>Fri, 15 Feb 2008 08:29:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:ef046ae9-bf0a-4b78-b095-53123a3bcdd8</guid>
      <author>Rick DeNatale</author>
      <link>http://talklikeaduck.denhaven2.com/articles/2008/02/15/best-practice-patterns-accessors-and-encapsulation</link>
      <category>ruby</category>
      <category>smalltalk</category>
      <category>best_practices</category>
      <category>kentbeck</category>
      <category>bestpracticepatterns</category>
      <category>patterns</category>
      <trackback:ping>http://talklikeaduck.denhaven2.com/articles/trackback/490</trackback:ping>
    </item>
    <item>
      <title>Yegge's At It Again!</title>
      <description>Another &lt;a href="http://steve-yegge.blogspot.com/2008/02/portrait-of-n00b.html"&gt;thought provoking piece from Steve Yegge.&lt;/a&gt;
&lt;blockquote&gt;Well, we also know that static types are just metadata. They&amp;#8217;re a specialized kind of comment targeted at two kinds of readers: programmers and compilers. Static types tell a story about the computation, presumably to help both reader groups understand the intent of the program. But the static types can be thrown away at runtime, because in the end they&amp;#8217;re just stylized comments. They&amp;#8217;re like pedigree paperwork: it might make a certain insecure personality type happier about their dog, but the dog certainly doesn&amp;#8217;t care. &amp;#8211; Steve Yegge&lt;/blockquote&gt;
&lt;p&gt;And he&amp;#8217;s getting the predictable responses from the static-typing advocates.&lt;/p&gt;
&lt;p&gt;One quibble I&amp;#8217;ve got with what I&amp;#8217;ve just quoted, is that, in many languages, static types aren&amp;#8217;t just comments.  In the C++ implementations I&amp;#8217;ve looked at, for example, the typing is used to generate runtime code which relies on the typing done at compile time.  The other day I wrote about instance variable access in Java, Smalltalk and Ruby.  In C++ instance variable (field) access is static and based on offsets.  If a type error get&amp;#8217;s past the compiler, say by a bad pointer manipulation, the run-time code can access a non-existant variable, possibly clobbering something vital.&lt;/p&gt;
&lt;p&gt;In fact this &amp;#8220;bug&amp;#8221; is possible not in spite of static type checking, but because the compiler uses static type checking to affect the code, and &amp;#8220;throws away&amp;#8221; the information needed at run-time to avoid it.&lt;/p&gt;</description>
      <pubDate>Tue, 12 Feb 2008 09:42:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:aede2c35-fcc8-4e8e-b7a6-a73b53e1441f</guid>
      <author>Rick DeNatale</author>
      <link>http://talklikeaduck.denhaven2.com/articles/2008/02/12/yegges-at-it-again</link>
      <category>ruby</category>
      <category>types</category>
      <category>statictyping</category>
      <trackback:ping>http://talklikeaduck.denhaven2.com/articles/trackback/489</trackback:ping>
    </item>
    <item>
      <title>Whose Variable Is It Anyway?</title>
      <description>&lt;p&gt;The more I think about Ruby in relation to other object programming languages I&amp;#8217;ve worked with, the more I realize that there&amp;#8217;s a continuum of static vs. dynamic typing.&lt;/p&gt;  
&lt;p&gt;Ruby fits close to one end of that continuum. Understanding this can help understand how to best use the language. I recently had a quick look at Russ Olsen&amp;#8217;s new book &lt;a href="http://www.amazon.com/gp/product/0321490452?ie=UTF8&amp;#38;tag=denhaven2com-20&amp;#38;linkCode=as2&amp;#38;camp=1789&amp;#38;creative=9325&amp;#38;creativeASIN=0321490452"&gt;Design Patterns in Ruby&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=denhaven2com-20&amp;#38;l=as2&amp;#38;o=1&amp;#38;a=0321490452" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt; and looked at his section on the observer pattern.  I&amp;#8217;d just posted to ruby-talk about this pattern, how it was implemented in Smalltalk, and a more Rubyish implementation.  I&amp;#8217;ll get to that at the end of this article, but first I really feel the urge to talk about instance variables.&lt;/p&gt;
&lt;p&gt;If we view a type as a particular interpretation of a memory layout, I see something like this&lt;/p&gt;

	&lt;table style="border:1px solid black;"&gt;
		&lt;tr&gt;
			&lt;th&gt;Language &lt;/th&gt;
			&lt;th&gt;Outside &lt;/th&gt;
			&lt;th&gt;inside &lt;/th&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt; Java &lt;/td&gt;
			&lt;td&gt; static &lt;/td&gt;
			&lt;td&gt; static &lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt; Smalltalk &lt;/td&gt;
			&lt;td&gt; encapsulated &lt;/td&gt;
			&lt;td&gt; static &lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt; Ruby &lt;/td&gt;
			&lt;td&gt; encapsulated &lt;/td&gt;
			&lt;td&gt; dynamic &lt;/td&gt;
		&lt;/tr&gt;
	&lt;/table&gt;




&lt;p&gt;The two columns represent how the object&amp;#8217;s innards &amp;#8220;look&amp;#8221; from outside the object, and inside the object (i.e. inside a method) respectively.&lt;/p&gt;

&lt;p&gt;In Java, subject to access modifiers, instance variables, a.k.a. fields, can be directly accessed.  No accessor method is required.  In Smalltalk and Ruby, instance variables of an object are only accessible while executing one of the object&amp;#8217;s methods.  Although both languages provide a bypass mechanism, instance_variable_get and instance_variable_set for Ruby; instVarAt: and instVarAt:put: for Smalltalk, these are both methods, and are to be used only in &amp;#8220;emergencies&amp;#8221; since they break the encapsulation of the object.&lt;/p&gt;

&lt;h2&gt;Static Instance Variable Binding&lt;/h2&gt;
&lt;p&gt;By static here, I mean that the code which accesses the instance variable uses information which is statically bound by the compiler. This is a subtlety which misses a lot of today&amp;#8217;s programmers &lt;a href="http://steve-yegge.blogspot.com/2007/06/rich-programmer-food.html"&gt;who don&amp;#8217;t understand what a compiler does,&lt;/a&gt; which is to take the textual, human written and readable source code and turn it into bits and bytes which can be executed by some form of computer.  The older wiser guys might just want to skim this section.&lt;/p&gt;
&lt;p&gt;That computer might be a real computer, like an Intel processor, or a virtual computer in the form of a software implemented virtual machine or interpreter. In the case of a real or virtual machine, there is an instruction set which gives the repertoire of the machine.  The program is executed by moving step by step, instruction by instruction. Now, if we have a simple C statement like:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_C "&gt;int a = b&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Then the instruction sequence for an imaginary computer might be something like:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;    load  reg2, 20(reg1)
    store reg2, 40(reg1)&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Which loads the second machine register from a word which is at an address 20 bytes after the address contained in machine register 1, and then stores that value into another word offset 40 bytes from register 1.  Here a and b are intended to be local temporary variables, and I&amp;#8217;ve decided that my compiler is using register 1 to point to the current activation stack frame.  Those magic numbers, 20 and 40 are computed by the compiler as part of it&amp;#8217;s function to map variables to memory locations.&lt;/p&gt;
&lt;p&gt;The idea that instructions might be different lengths is quite common in instruction set design.  Usually some number of bits at the beginning of the instruction is used to encode an &amp;#8216;op code&amp;#8217; like load or store, add, or subtract, etc.  Other bits are used to determine the presence and format of parameters for the operation.  Different instruction sets have different addressing modes, which allow memory to be addressed in various ways, such as the mode used above which addresses memory as an offset from a location held in a register. Other addressing modes might add another register used to index elements in an array, for example. Most real instruction sets have some unit of length for instructions, so for a given machine architecture, all instructions might be one or more words, or one or more bytes.&lt;/p&gt;
&lt;h2&gt;Bytecodes Are An Instruction Set Format&lt;/h2&gt;
&lt;p&gt;The term &amp;#8220;bytecode&amp;#8221; is simply a particular form of an instruction set, or rather a family of forms.  Most people associate the term with Java, and a particular instruction set, although the term predates Java, being used by Smalltalk and probably before.  It really means that the &amp;#8216;machine code&amp;#8217; instructions are represented as a series of bytes.  Many instructions are encoded by a single byte, although some require additional bytes in order to form a complete instruction. The general term bytecode simply means that the length unit for the instruction set is one byte.&lt;/p&gt;
&lt;p&gt;Although Java and Smalltalk implementations typically use bytecode instruction sets for their virtual machines, the actual set of bytecodes differs, much as the instruction set for an Intel Core Duo 2, differs from the instruction set for a PowerPC G4.&lt;/p&gt;
&lt;h2&gt;Classical Instance Variable Binding, Smalltalk Style&lt;/h2&gt;
&lt;p&gt;Now lets look at similar code in Smalltalk.  In this article, I&amp;#8217;m using the bytecodes defined by the out of print, &amp;#8220;Smalltalk:The Language and Its Implementation&amp;#8221;, a.k.a. &amp;#8220;The Blue Book&amp;#8221;, other Smalltalk implementations might be slightly different.&lt;/p&gt;
&lt;p&gt;Let&amp;#8217;s say that a and b here are instance variables.  The Smalltalk bytecodes&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;    a := b&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Would look something like:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;    push_iv_4            # push instance-variable #4 
                             # onto the stack
    store_and_pop_iv_6   # store the top of the stack in
                             # instance-variable #6&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;In Smalltalk, those magic index numbers used to access instance variables are determined when the class definition is saved. In this case b turned out to be the 4th instance variable, and a the 6th.  Smalltalk bytecodes are optimized for small objects, the first 16 instance variables can all be pushed or popped with a single-byte instruction, if an object has more than 16 instance variables then those beyond the 16th need to be accessed via an extended push or store instruction, which allows up to 64 instance variables to be accessed.&lt;/p&gt;
&lt;p&gt;In Smalltalk, although instance variables aren&amp;#8217;t &lt;strong&gt;typed&lt;/strong&gt;, they are &lt;strong&gt;declared&lt;/strong&gt; in a class definition message executed when the class definition is saved.  Any time a class definition is saved, the indices for the instance variables of that class, and of any subclasses are (re)computed, and any methods in the class and it&amp;#8217;s subclasses are re-compiled to adjust the offsets. The instance variables defined in the topmost class get the first n offsets, each immediate subclasses instance variables get sequential offsets starting with the next available, and so forth.&lt;/p&gt;
&lt;p&gt;This is why I said above that inside a Smalltalk object, i.e. within it&amp;#8217;s methods, the object is mapped statically.  Changing the instance variable definitions requires re-compilation to avoid &amp;#8216;type-errors&amp;#8217; in the methods.&lt;/p&gt;
&lt;p&gt;Note that those &amp;#8216;emergency-only&amp;#8217; methods instvarAt: and instVarAt:put: map to the push_iv and store_and_pop_iv bytecodes, the first argument to both is the instance variable index.  This also means that they need to be used with care, since you need to know the offset of the instance variable. Now, at least Smalltalk can tell you if you try to access a non-existant instance variable slot but it can&amp;#8217;t tell that you&amp;#8217;re accessing the &lt;strong&gt;wrong&lt;/strong&gt; slot.&lt;/p&gt;
&lt;h2&gt;Java Field Binding&lt;/h2&gt;
&lt;p&gt;In Java, offsets are not compiled directly into the bytecodes, there&amp;#8217;s a level of indirection. Peter Haggar, with whom  I used to work at &lt;span class="caps"&gt;IBM&lt;/span&gt; wrote an &lt;a href="http://www.ibm.com/developerworks/ibm/library/it-haggar_bytecode/"&gt;article on Java bytecodes&lt;/a&gt; on developerworks. I hope he won&amp;#8217;t mind if I borrow one of his examples. Here&amp;#8217;s a simple accessor method&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;public String employeeName()
{
    return name;
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
And the resultant bytecodes. (The 0, 1, and 4 are offsets from the beginning of the method)
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;    Method java.lang.String employeeName()
    0 aload_0
    1 getfield #5 &amp;lt;Field java.lang.String name&amp;gt;
    4 areturn&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;What this code does first is to push a reference to the current object, &lt;strong&gt;this&lt;/strong&gt;, onto the stack.  Then the getfield instruction uses it&amp;#8217;s operand to replace the top two items on the stack with the value of the field.  So these two byte-codes (actually 3 bytes in total) are roughly equivalent to the Smalltalk push_iv bytecode, but for two differences:&lt;/p&gt;
&lt;ol&gt;
    &lt;li&gt;The Smalltalk push_iv opcode implicitly uses the receiver of the current method, whereas the getfield opcode needs another argument referencing the object whose instance variable is being accessed.&lt;/li&gt;
    &lt;li&gt;In Smalltalk the argument identifying the variable is an integer index, but in Java the argument is actually a reference to a field descriptor associated with the class of the object whose instance variable is being referenced.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The first difference is because in Java, unlike in Smalltalk, you can directly get and set public fields outside of of the objects methods, so since the object in question isn&amp;#8217;t implied, it has to be specified.&lt;/p&gt;
&lt;p&gt;The second difference is to allow for separate compilation.  The actual Java VM specification doesn&amp;#8217;t dictate how fields are mapped within objects, but the abstraction is to allow this mapping to be adjusted at the time classes are loaded.  If a subclass is compiled separately from it&amp;#8217;s superclass, it might get a new starting position for it&amp;#8217;s fields everytime it&amp;#8217;s loaded if one or it&amp;#8217;s superclasses has added or removed fields.&lt;/p&gt;
&lt;p&gt;So in order to access a Java field, the compiler needs to know the type of the object containing the field.  This is true whether we are inside a method or outside.&lt;/p&gt;
&lt;h2&gt;Instance Variables, The Ruby Way&lt;/h2&gt;
&lt;p&gt;In Ruby, instance variables aren&amp;#8217;t declared, so offsets can&amp;#8217;t be assigned statically. Instead, Ruby looks up instance variables dynamically, using the instance variable &lt;strong&gt;name&lt;/strong&gt; rather than an offset. Again this matches the &amp;#8216;emergency use&amp;#8217; messages, instance_variable_get and instance_variable_set take an instance variable name, complete with the &amp;#8221;@&amp;#8221; sigil, where the Smalltalk instVarAt: methods take an integer.&lt;/p&gt;
&lt;p&gt;In Ruby 1.8, this lookup is implemented in a fairly straightforward fashion. With a few exceptions, which I won&amp;#8217;t take the time to go into here, a Ruby object has a pointer named iv_tbl which points to a hash table which maps the instance variable names to values.  In Ruby 1.9, the implementation is a bit more clever, but the effects are the same.&lt;/p&gt;
&lt;h2&gt;So Whose Variable IS it Anyway?&lt;/h2&gt;
&lt;p&gt;Which brings us back to the title of this article.  In Java and Smalltalk, every instance of a given class has the same set of instance variables, albeit each with it&amp;#8217;s own value. The variables come into existence when they are declared, and the class is compiled or the class definition is saved.&lt;/p&gt;
&lt;p&gt;One thing I didn&amp;#8217;t mention in the discussion of Smalltalk is that, because traditional Smalltalk implementations don&amp;#8217;t separate the development environment from the run-time environment, when a class definition changes, besides requiring method recompilation for the class and it&amp;#8217;s subclasses, any existing instance variables need to be mutated to either add or remove the changed instance variables.  Back when he was working on the language self, which has dynamic resolution of instance variables like Ruby, Dave Ungar used to like to kill various Smalltalk implementations by adding an instance variable to the Object class.  The problem is that because we are trying to operate on the running system, the system usually trips over itself during such a change.  I tried this a few weeks ago with Squeak, and although it warned me twice that I shouldn&amp;#8217;t do that, it did try when I clicked that second &amp;#8220;Are you sure&amp;#8221; button, and crashed pretty quickly. Ruby does handle this as a matter of course, since instance variables are only added to individual objects when they are needed, and self inside a method really is duck-typed, actually more than duck-typed, since the needed instance variables appear just in time.&lt;/p&gt;
&lt;h2&gt;So you mentioned the Observer Pattern, What&amp;#8217;s All This Have To Do With That&lt;/h2&gt;
&lt;p&gt;One of the things which got me thinking about this again was a thread on ruby-talk some weeks ago about Ruby garbage collection and some of the things which keep Object from being considered garbage and being collected.  The Ruby GC tends to have problems if you use finalization and aren&amp;#8217;t &lt;strong&gt;really&lt;/strong&gt; careful about how you define your finalizers.&lt;/p&gt;
&lt;p&gt;One of the classic gotcha&amp;#8217;s in Smalltalk in this vein is the implementation of Object dependents, a.k.a. the Observer Pattern.  Smalltalk provides a mechanism to add dependent objects to any other object which, when it want&amp;#8217;s to notify it&amp;#8217;s dependents that it has changed, can simply send itself the changed message, which in turn sends each dependent the message update: with the changed object as the argument.&lt;/p&gt;
&lt;p&gt;This is the basis of the Model View Controller design in Smalltalk. Views register as dependents on Models, and when a model changes, any Views depending on it can react. This is the genesis of the Observer pattern from the &lt;a href="http://www.amazon.com/gp/product/0201633612?ie=UTF8&amp;#38;tag=denhaven2com-20&amp;#38;linkCode=as2&amp;#38;camp=1789&amp;#38;creative=9325&amp;#38;creativeASIN=0201633612"&gt;well known gang of four Design Patterns book&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=denhaven2com-20&amp;#38;l=as2&amp;#38;o=1&amp;#38;a=0201633612" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt; where Model, and View have been generalized to Subject and Observer respectively.&lt;/p&gt;
&lt;p&gt;In Smalltalk the ability to manage a list of dependents and notify them on changes is something that every object can do, but very few objects actually use this capability.  In order to avoid having an instance variable in every Smalltalk object to reference a dependents collection which is almost always empty, the default implementation actually keeps a global hash which maps objects with dependents to their dependent collection.&lt;/p&gt;
&lt;p&gt;The problem with this default implementation is that once an object gains a dependent, the object and it&amp;#8217;s dependent objects are permanently reachable, and therefore ineligible for garbage collection, unless the dependency is explicitly removed.  As a result of this, the classes of most objects which actually &lt;strong&gt;have&lt;/strong&gt; dependents reimplement the default methods to refer to the dependents collection via an instance value in the object with dependents. Squeak, for example provides a subclass of object called Model which provides such a GC friendly implementation.&lt;/p&gt;
&lt;p&gt;Which brings me to the implementation of the observer pattern in Ruby.  In his discussion of this pattern in his book, Russ Olsen provides a module which can be mixed into an object to allow it to have dependents:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_ruby "&gt;&lt;span class="keyword"&gt;module &lt;/span&gt;&lt;span class="module"&gt;Subject&lt;/span&gt;
  &lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;initialize&lt;/span&gt;
    &lt;span class="attribute"&gt;@observers&lt;/span&gt; &lt;span class="punct"&gt;=&lt;/span&gt; &lt;span class="punct"&gt;[]&lt;/span&gt;
  &lt;span class="keyword"&gt;end&lt;/span&gt;

  &lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;add_observer&lt;/span&gt;&lt;span class="punct"&gt;(&amp;amp;&lt;/span&gt;&lt;span class="ident"&gt;observer&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt;
    &lt;span class="attribute"&gt;@observers&lt;/span&gt; &lt;span class="punct"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="ident"&gt;observer&lt;/span&gt;
  &lt;span class="keyword"&gt;end&lt;/span&gt;

  &lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;delete_observer&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="ident"&gt;observer&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt;
    &lt;span class="attribute"&gt;@observers&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;delete&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="ident"&gt;observer&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt;
  &lt;span class="keyword"&gt;end&lt;/span&gt;

  &lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;notify_observers&lt;/span&gt;
    &lt;span class="attribute"&gt;@observers&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;each&lt;/span&gt; &lt;span class="keyword"&gt;do&lt;/span&gt; &lt;span class="punct"&gt;|&lt;/span&gt;&lt;span class="ident"&gt;observer&lt;/span&gt;&lt;span class="punct"&gt;|&lt;/span&gt;
      &lt;span class="ident"&gt;observer&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;call&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="constant"&gt;self&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt;
    &lt;span class="keyword"&gt;end&lt;/span&gt;
  &lt;span class="keyword"&gt;end&lt;/span&gt;  
&lt;span class="keyword"&gt;end&lt;/span&gt;    &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This is a nice Ruby spin on the pattern, in that the Observers can be blocks, or any other object which responds to a call method which takes the Subject as its argument.&lt;/p&gt;
&lt;p&gt;Shortly before seeing the book, as a result of that GC thread, I&amp;#8217;d written my own variation on this, which let&amp;#8217;s any object be a subject, by opening up the Object class:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_ruby "&gt;&lt;span class="keyword"&gt;class &lt;/span&gt;&lt;span class="class"&gt;Object&lt;/span&gt;
    &lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;add_observer&lt;/span&gt;&lt;span class="punct"&gt;(&amp;amp;&lt;/span&gt;&lt;span class="ident"&gt;observer&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt;
      &lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="attribute"&gt;@observers&lt;/span&gt; &lt;span class="punct"&gt;||=&lt;/span&gt; &lt;span class="punct"&gt;[])&lt;/span&gt; &lt;span class="punct"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="ident"&gt;observer&lt;/span&gt;
    &lt;span class="keyword"&gt;end&lt;/span&gt;

    &lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;delete_observer&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="ident"&gt;observer&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt;
      &lt;span class="ident"&gt;observers&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;delete&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="ident"&gt;observer&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt;
    &lt;span class="keyword"&gt;end&lt;/span&gt;

    &lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;notify_observers&lt;/span&gt;
      &lt;span class="ident"&gt;observers&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;each&lt;/span&gt; &lt;span class="keyword"&gt;do&lt;/span&gt; &lt;span class="punct"&gt;|&lt;/span&gt;&lt;span class="ident"&gt;observer&lt;/span&gt;&lt;span class="punct"&gt;|&lt;/span&gt;
        &lt;span class="ident"&gt;observer&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;call&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="constant"&gt;self&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt;
      &lt;span class="keyword"&gt;end&lt;/span&gt;
    &lt;span class="keyword"&gt;end&lt;/span&gt;

    &lt;span class="ident"&gt;private&lt;/span&gt;
    &lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;observers&lt;/span&gt;
      &lt;span class="attribute"&gt;@observers&lt;/span&gt; &lt;span class="punct"&gt;||&lt;/span&gt; &lt;span class="punct"&gt;[]&lt;/span&gt;
    &lt;span class="keyword"&gt;end&lt;/span&gt; 
&lt;span class="keyword"&gt;end&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Because of the fact that Ruby only adds instance variables on the fly as needed, we get the benefit of universal support for objects to be Subjects without requiring an observers instance variable for those objects which don&amp;#8217;t. The only cost is the potential namespace collision for the four method names.&lt;/p&gt;
&lt;h2&gt;Another Use of Dynamic Instance Variables&lt;/h2&gt;
&lt;p&gt;Recently I wrote an &lt;a href="http://www.infoq.com/news/2008/01/rails-resource-controller"&gt;article for InfoQ&lt;/a&gt; about &lt;a href="http://jamesgolick.com/resource_controller"&gt;James Golick&amp;#8217;s resource_controller plugin for Rails&lt;/a&gt; which allows you to write Rails controllers for RESTful resources which can automatically adapt for use in different resource nesting contexts.  This plugin makes good use of the dynamic nature of Ruby instance variables, automatically defining different instance variables in the controller to correspond to the end resource and each of its parent resources.&lt;/p&gt;
&lt;h2&gt;Whew!&lt;/h2&gt;
&lt;p&gt;This has turned out to be a rather long article, which I&amp;#8217;ve been meaning to write for some time.  I hope that someone finds it useful, or at least interesting.&lt;/p&gt;</description>
      <pubDate>Fri, 08 Feb 2008 16:14:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:bfb1599b-784b-403b-8fdf-90e68ecaa897</guid>
      <author>Rick DeNatale</author>
      <link>http://talklikeaduck.denhaven2.com/articles/2008/02/08/whose-variable-is-it-anyway</link>
      <category>ruby</category>
      <category>smalltalk</category>
      <category>java</category>
      <category>binding</category>
      <category>variables</category>
      <trackback:ping>http://talklikeaduck.denhaven2.com/articles/trackback/487</trackback:ping>
    </item>
    <item>
      <title>Validating RSS Feeds with RSpec</title>
      <description>&lt;p&gt;One of my current Rails projects involves generating an RSS feed.  While I was working on this the other night, it seemed to be working, so I deployed it to the staging server. Everything looked fine. If I fetched it with Firefox, the browser offered to let me subscribe to the feed with Google Reader, and if I used Safari I'd see a nice view of the feed just like I expected.&lt;/p&gt;
&lt;p&gt;So I sent a note via our campfire to check it out, and a colleague replied that &lt;strong&gt;his&lt;/strong&gt; Safari was saying that it was in an invalid format.&lt;/p&gt;
&lt;p&gt;So I went to the &lt;a href="http://validator.w3.org/feed/"&gt;W3 RSS Feed Validation Service&lt;/a&gt; and worked through the validation issues, after which his browser was as happy as mine.&lt;/p&gt;
&lt;p&gt;Of course, having been through that, I wanted to make sure that RSS validation was covered in the specs for the project.&lt;/p&gt;
&lt;p&gt;I went looking for an existing RSpec matcher, and found &lt;a href="http://www.anodyne.ca/2007/09/28/rspec-custom-matchers-and-be_valid_xhtml/"&gt;a matcher to validate XHTML&lt;/a&gt; but nothing for RSS.&lt;/p&gt;
&lt;p&gt;I then found the &lt;a href="http://feedvalidator.rubyforge.org/"&gt;feedvalidator gem&lt;/a&gt; which provides a Ruby interface to the SOAP interface to the W3 feed validator.  You would think that W3 would be providing a REST interface!  The gem already provides assertions for use with Test::Unit, so I just built an RSpec matcher.&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_ruby "&gt;&lt;notextile&gt;&lt;span class="keyword"&gt;class &lt;/span&gt;&lt;span class="class"&gt;BeValidFeed&lt;/span&gt;
  &lt;span class="ident"&gt;require&lt;/span&gt; &lt;span class="punct"&gt;'&lt;/span&gt;&lt;span class="string"&gt;feed_validator&lt;/span&gt;&lt;span class="punct"&gt;'&lt;/span&gt;
  &lt;span class="ident"&gt;require&lt;/span&gt; &lt;span class="punct"&gt;'&lt;/span&gt;&lt;span class="string"&gt;tmpdir&lt;/span&gt;&lt;span class="punct"&gt;'&lt;/span&gt;
  &lt;span class="ident"&gt;require&lt;/span&gt; &lt;span class="punct"&gt;'&lt;/span&gt;&lt;span class="string"&gt;md5&lt;/span&gt;&lt;span class="punct"&gt;'&lt;/span&gt;

  &lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;matches?&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="ident"&gt;response&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt;
    &lt;span class="keyword"&gt;return&lt;/span&gt; &lt;span class="constant"&gt;true&lt;/span&gt; &lt;span class="keyword"&gt;if&lt;/span&gt; &lt;span class="ident"&gt;validity_checks_disabled?&lt;/span&gt;
    &lt;span class="ident"&gt;v&lt;/span&gt; &lt;span class="punct"&gt;=&lt;/span&gt; &lt;span class="constant"&gt;W3C&lt;/span&gt;&lt;span class="punct"&gt;::&lt;/span&gt;&lt;span class="constant"&gt;FeedValidator&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;new&lt;/span&gt;&lt;span class="punct"&gt;()&lt;/span&gt;
    &lt;span class="ident"&gt;fragment&lt;/span&gt; &lt;span class="punct"&gt;=&lt;/span&gt; &lt;span class="ident"&gt;response&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;body&lt;/span&gt;
    &lt;span class="ident"&gt;filename&lt;/span&gt; &lt;span class="punct"&gt;=&lt;/span&gt; &lt;span class="constant"&gt;File&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;join&lt;/span&gt; &lt;span class="constant"&gt;Dir&lt;/span&gt;&lt;span class="punct"&gt;::&lt;/span&gt;&lt;span class="ident"&gt;tmpdir&lt;/span&gt;&lt;span class="punct"&gt;,&lt;/span&gt; &lt;span class="punct"&gt;'&lt;/span&gt;&lt;span class="string"&gt;feed.&lt;/span&gt;&lt;span class="punct"&gt;'&lt;/span&gt; &lt;span class="punct"&gt;+&lt;/span&gt; &lt;span class="constant"&gt;MD5&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;md5&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="ident"&gt;fragment&lt;/span&gt;&lt;span class="punct"&gt;).&lt;/span&gt;&lt;span class="ident"&gt;to_s&lt;/span&gt;
    &lt;span class="keyword"&gt;begin&lt;/span&gt;
      &lt;span class="ident"&gt;response&lt;/span&gt; &lt;span class="punct"&gt;=&lt;/span&gt; &lt;span class="constant"&gt;File&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;open&lt;/span&gt; &lt;span class="ident"&gt;filename&lt;/span&gt; &lt;span class="keyword"&gt;do&lt;/span&gt; &lt;span class="punct"&gt;|&lt;/span&gt;&lt;span class="ident"&gt;f&lt;/span&gt;&lt;span class="punct"&gt;|&lt;/span&gt; &lt;span class="constant"&gt;Marshal&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;load&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="ident"&gt;f&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt; &lt;span class="keyword"&gt;end&lt;/span&gt;
      &lt;span class="ident"&gt;v&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;parse&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="ident"&gt;response&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt;
  	&lt;span class="keyword"&gt;rescue&lt;/span&gt;   
      &lt;span class="keyword"&gt;unless&lt;/span&gt; &lt;span class="ident"&gt;v&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;validate_data&lt;/span&gt;&lt;span class="punct"&gt;(&lt;/span&gt;&lt;span class="ident"&gt;fragment&lt;/span&gt;&lt;span class="punct"&gt;)&lt;/span&gt;
        &lt;span class="attribute"&gt;@failure&lt;/span&gt; &lt;span class="punct"&gt;=&lt;/span&gt; &lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;&lt;span class="string"&gt; could not access w3 validator to validate the feed.&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;
        &lt;span class="keyword"&gt;return&lt;/span&gt; &lt;span class="constant"&gt;false&lt;/span&gt;
      &lt;span class="keyword"&gt;end&lt;/span&gt;
      &lt;span class="constant"&gt;File&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;open&lt;/span&gt; &lt;span class="ident"&gt;filename&lt;/span&gt;&lt;span class="punct"&gt;,&lt;/span&gt; &lt;span class="punct"&gt;'&lt;/span&gt;&lt;span class="string"&gt;w+&lt;/span&gt;&lt;span class="punct"&gt;'&lt;/span&gt; &lt;span class="keyword"&gt;do&lt;/span&gt; &lt;span class="punct"&gt;|&lt;/span&gt;&lt;span class="ident"&gt;f&lt;/span&gt;&lt;span class="punct"&gt;|&lt;/span&gt; &lt;span class="constant"&gt;Marshal&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;dump&lt;/span&gt; &lt;span class="ident"&gt;v&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;response&lt;/span&gt;&lt;span class="punct"&gt;,&lt;/span&gt; &lt;span class="ident"&gt;f&lt;/span&gt; &lt;span class="keyword"&gt;end&lt;/span&gt;
  	&lt;span class="keyword"&gt;end&lt;/span&gt;
    &lt;span class="ident"&gt;v&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;valid?&lt;/span&gt;   
  &lt;span class="keyword"&gt;end&lt;/span&gt;

  &lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;description&lt;/span&gt;
    &lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;be valid xhtml&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;
  &lt;span class="keyword"&gt;end&lt;/span&gt;

  &lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;failure_message&lt;/span&gt;
   &lt;span class="attribute"&gt;@failure&lt;/span&gt; &lt;span class="punct"&gt;||&lt;/span&gt; &lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;&lt;span class="string"&gt; expected xhtml to be valid, but validation produced these errors:&lt;span class="escape"&gt;\n&lt;/span&gt; &lt;span class="expr"&gt;#{@message}&lt;/span&gt;&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;
  &lt;span class="keyword"&gt;end&lt;/span&gt;

  &lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;negative_failure_message&lt;/span&gt;
    &lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;&lt;span class="string"&gt; expected to not be valid, but was (missing validation?)&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;&lt;/span&gt;
  &lt;span class="keyword"&gt;end&lt;/span&gt;

  &lt;span class="ident"&gt;private&lt;/span&gt;
    &lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;validity_checks_disabled?&lt;/span&gt;
      &lt;span class="constant"&gt;ENV&lt;/span&gt;&lt;span class="punct"&gt;[&amp;quot;&lt;/span&gt;&lt;span class="string"&gt;NONET&lt;/span&gt;&lt;span class="punct"&gt;&amp;quot;]&lt;/span&gt; &lt;span class="punct"&gt;==&lt;/span&gt; &lt;span class="punct"&gt;'&lt;/span&gt;&lt;span class="string"&gt;true&lt;/span&gt;&lt;span class="punct"&gt;'&lt;/span&gt;
    &lt;span class="keyword"&gt;end&lt;/span&gt;
&lt;span class="keyword"&gt;end&lt;/span&gt;

&lt;span class="keyword"&gt;def &lt;/span&gt;&lt;span class="method"&gt;be_valid_feed&lt;/span&gt;
  &lt;span class="constant"&gt;BeValidFeed&lt;/span&gt;&lt;span class="punct"&gt;.&lt;/span&gt;&lt;span class="ident"&gt;new&lt;/span&gt;
&lt;span class="keyword"&gt;end&lt;/span&gt;&lt;/notextile&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;I saved this as spec/be_valid_feed.rb&lt;/p&gt;

&lt;p&gt;And in a view or controller spec, I can include this file, and test a response with:&lt;/p&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;&lt;notextile&gt;response.should be_valid_feed&lt;/notextile&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;If you use this in a controller spec, you will need to tell RSpec to integrate_views, or you won't have much of a feed to check.  If you use nested example groups, integrate_views needs to be inside the inner group.&lt;/p&gt;

</description>
      <pubDate>Fri, 08 Feb 2008 10:38:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:0b27f7ba-403b-48c5-9833-2fd2b5d73fa8</guid>
      <author>Rick DeNatale</author>
      <link>http://talklikeaduck.denhaven2.com/articles/2008/02/08/validating-rss-feeds-with-rspec</link>
      <category>ruby</category>
      <category>best_practices</category>
      <category>rails</category>
      <category>Rspec</category>
      <category>rss</category>
      <category>validation</category>
      <trackback:ping>http://talklikeaduck.denhaven2.com/articles/trackback/486</trackback:ping>
    </item>
    <item>
      <title>Why I Don't Mind Using RSpec - In Fact I've Come to Love It.</title>
      <description>&lt;p&gt;About a year ago when I first encountered RSpec, I thought that the idea sounded good, but I was concerned about how much the implementation at that time pushed new methods into Object and Kernel. It felt to me as though it could interfere with the code being specified/tested. Indeed back then there were some problems when RSpec and Rails bumped heads over the use of certain Ruby metaprogramming techniques.  I&amp;#8217;d been a &lt;span class="caps"&gt;TDD&lt;/span&gt; user advocate for many years, heck I was there right after Kent Beck, &amp;#8220;test-infected&amp;#8221; Erich Gamma and sat in on some of their early pairing sessions during an annual &lt;span class="caps"&gt;OTI&lt;/span&gt; company technical conference at Montebello in Quebec, when JUnit was in it&amp;#8217;s infancy.  The cleaner language of RSpec did have it&amp;#8217;s attractions, particularly in trying to get across the idea to newcomers that &lt;span class="caps"&gt;TDD&lt;/span&gt; was really writing mini-specifications rather than tests, which helps put them in the right mindset, but for those of us who had already crossed that paradigm shift, or been born on the right side of it, it didn&amp;#8217;t seem so important.&lt;/p&gt;


	&lt;p&gt;Since then the RSpec implementation has matured, and after talking to David Chelimsky and Dave Astels at RubyConf, I decided to give it another look, and, armed with a new perspective on the use of mocks and stubs to isolate specifications and tests in &lt;span class="caps"&gt;BDD&lt;/span&gt;/TDD, I quickly became a convert.  I still use other frameworks as external requirements dictate, but RSpec has become my first choice.&lt;/p&gt;


	&lt;p&gt;These days, though the choice of testing/specification framework seems to have become one of those religious issues which divide the community, almost as much as emacs vs. vim vs. textmate.  I run into people all the time who reject RSpec because it&amp;#8217;s &amp;#8220;too magical!&amp;#8221;  Although I&amp;#8217;ve never been able to get them to expand on that thought. Perhaps it&amp;#8217;s based on the kind of concerns I had about it at first, maybe it&amp;#8217;s something else.  I&amp;#8217;d love to have it explained.&lt;/p&gt;


	&lt;p&gt;And like advocates do, other arguments get expressed, some of which don&amp;#8217;t get the scrutiny they deserve.&lt;/p&gt;


	&lt;p&gt;For example, a few days ago Rob Sanheim, someone I know and respect, wrote about why &lt;a href="http://robsanheim.com/2008/01/25/why-i-use-testspec-over-rspec/"&gt;he eschews RSpec for Test::Spec&lt;/a&gt;. His basic, quite brief argument is that because RSpec is 10 times bigger in terms of lines of code than Test::Spec it must be worse.&lt;/p&gt;


&lt;h2&gt;How to Lie with Statistics&lt;/h2&gt;
Nice statistics, but back when I was in college, one of the must-read books was &amp;#8220;How to Lie with Statistics&amp;#8221;.  Given the right pick of statistics you can prove anything.

	&lt;p&gt;First off I think that Rob was unfair to lump the lib and spec or test directories together.  Even if you might believe that code bulk is bad, I think that it&amp;#8217;s reasonable to think of the code bulk in the implementation to be like &amp;#8216;bad cholesterol&amp;#8217;, and test-code which verifies that implementation as &amp;#8216;good cholesterol.&amp;#8217;  Most of you are probably too young to be concerned about it yet, but my doctors tell me that a high &lt;span class="caps"&gt;HDL&lt;/span&gt;/LDL ratio is more important than an absolute &lt;span class="caps"&gt;HDL&lt;/span&gt;+LDL.  The theory at least is that the &lt;span class="caps"&gt;HDL&lt;/span&gt; helps sweep the &lt;span class="caps"&gt;LDL&lt;/span&gt; out of the vessels, kind of like a good test suite keeps code under control.&lt;/p&gt;


	&lt;p&gt;Here are the numbers I get running sloccount on the latest RSpec and test/unit gems:&lt;/p&gt;


	&lt;table style="border:1px solid black; align:right;"&gt;
		&lt;tr&gt;
			&lt;th&gt;Framework &lt;/th&gt;
			&lt;th&gt;lib &lt;/th&gt;
			&lt;th&gt;spec/test&lt;/th&gt;
			&lt;th&gt;test/code ratio &lt;/th&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt; Rspec &lt;/td&gt;
			&lt;td&gt; 5473 &lt;/td&gt;
			&lt;td&gt;10108  &lt;/td&gt;
			&lt;td&gt; 1.8 &lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt; Test::Spec &lt;/td&gt;
			&lt;td&gt; 275 &lt;/td&gt;
			&lt;td&gt; 879 &lt;/td&gt;
			&lt;td&gt; 3.2 &lt;/td&gt;
		&lt;/tr&gt;
	&lt;/table&gt;




	&lt;p&gt;So at first blush it looks bad for RSpec, Test::Spec even tests itself more thoroughly!&lt;/p&gt;


	&lt;p&gt;The real problem with Rob&amp;#8217;s post is that he&amp;#8217;s comparing Apple seeds with Apples.  Of course Test::Spec is considerably smaller than RSpec, it&amp;#8217;s a bump on Test::Unit to add the new assertion style.  So we need to at least add Test::Unit&amp;#8217;s numbers&lt;/p&gt;


	&lt;table style="border:1px solid black; align:right;"&gt;
		&lt;tr&gt;
			&lt;th&gt;Framework &lt;/th&gt;
			&lt;th&gt;lib &lt;/th&gt;
			&lt;th&gt;spec/test&lt;/th&gt;
			&lt;th&gt;test/code ratio &lt;/th&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt; Test:Unit &lt;/td&gt;
			&lt;td&gt; 2741 &lt;/td&gt;
			&lt;td&gt; 0 &lt;/td&gt;
			&lt;td&gt; 0 &lt;/td&gt;
		&lt;/tr&gt;
	&lt;/table&gt;




	&lt;p&gt;Now I&amp;#8217;m sure that Nathaniel &amp;#8220;ate his own dog food&amp;#8221; when he developed Test::Unit, and Ryan is continuing to dine on it, now that he&amp;#8217;s taken over its maintenance, but that dog food apparently doesn&amp;#8217;t leave home.  Now if we look at the combination of Test::Unit and Test::Spec the comparison looks like this:&lt;/p&gt;


	&lt;table style="border:1px solid black; align:right;"&gt;
		&lt;tr&gt;
			&lt;th&gt;Framework &lt;/th&gt;
			&lt;th&gt;lib &lt;/th&gt;
			&lt;th&gt;spec/test&lt;/th&gt;
			&lt;th&gt;test/code ratio &lt;/th&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt; Rspec &lt;/td&gt;
			&lt;td&gt; 5473 &lt;/td&gt;
			&lt;td&gt;10108  &lt;/td&gt;
			&lt;td&gt; 1.8 &lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt; TU+TS &lt;/td&gt;
			&lt;td&gt; 2713 &lt;/td&gt;
			&lt;td&gt; 879 &lt;/td&gt;
			&lt;td&gt; 0.3 &lt;/td&gt;
		&lt;/tr&gt;
	&lt;/table&gt;




	&lt;p&gt;So RSpec looks a little better, particularly when it comes to eating it&amp;#8217;s own dog food.&lt;/p&gt;


	&lt;p&gt;But, as that Billy Mays guy on the Infomercials is wont to say, &amp;#8220;Wait! There&amp;#8217;s more!&amp;#8221;.&lt;/p&gt;


	&lt;p&gt;RSpec also includes a built-in mocking framework, now with the &amp;#8216;traditional&amp;#8217; choice you need to throw in your choice of mock framework, here&amp;#8217;s are the stats for Flexmock and Mocha&lt;/p&gt;


	&lt;table style="border:1px solid black; align:right;"&gt;
		&lt;tr&gt;
			&lt;th&gt;Framework &lt;/th&gt;
			&lt;th&gt;lib &lt;/th&gt;
			&lt;th&gt;spec/test&lt;/th&gt;
			&lt;th&gt;test/code ratio &lt;/th&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt; Flexmock &lt;/td&gt;
			&lt;td&gt; 1034  &lt;/td&gt;
			&lt;td&gt; 2743 &lt;/td&gt;
			&lt;td&gt; 2.6 &lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt; Mocha    &lt;/td&gt;
			&lt;td&gt; 1218  &lt;/td&gt;
			&lt;td&gt; 3622 &lt;/td&gt;
			&lt;td&gt; 2.8 &lt;/td&gt;
		&lt;/tr&gt;
	&lt;/table&gt;




	&lt;p&gt;So now we&amp;#8217;ve got two sub-variants to look at:&lt;/p&gt;


	&lt;table style="border:1px solid black; align:right;"&gt;
		&lt;tr&gt;
			&lt;th&gt;Framework &lt;/th&gt;
			&lt;th&gt;lib &lt;/th&gt;
			&lt;th&gt;spec/test&lt;/th&gt;
			&lt;th&gt;test/code ratio &lt;/th&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt; Rspec &lt;/td&gt;
			&lt;td&gt; 5473 &lt;/td&gt;
			&lt;td&gt;10108  &lt;/td&gt;
			&lt;td&gt; 1.8 &lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt; TU+TS+FM &lt;/td&gt;
			&lt;td&gt; 3747 &lt;/td&gt;
			&lt;td&gt; 3622 &lt;/td&gt;
			&lt;td&gt; 1.0 &lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt; TU+TS+Mocha &lt;/td&gt;
			&lt;td&gt; 3931 &lt;/td&gt;
			&lt;td&gt;  3931 &lt;/td&gt;
			&lt;td&gt; 1.1 &lt;/td&gt;
		&lt;/tr&gt;
	&lt;/table&gt;




	&lt;p&gt;Now you might say that RSpec still is 40% larger than even the larger of the two competing combinations, but this is also ignoring the fact that RSpec also includes RBehave which is another higher level integration/acceptance testing framework.&lt;/p&gt;


	&lt;p&gt;So in retrospect, I&amp;#8217;d humbly submit that code bulk isn&amp;#8217;t such a good comparison criteria in this case.&lt;/p&gt;


	&lt;p&gt;So whatever your test framework &amp;#8216;belief system&amp;#8217; do as you feel best, but do unto others!&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;d still like to hear more about why people think that RSpec is &amp;#8220;too magic&amp;#8221; though.&lt;/p&gt;


	&lt;p&gt;By the way on the subject of lying statistics.  I&amp;#8217;m sure that most of us have by now seen &lt;a href="http://www.indeed.com/jobtrends?q=ruby%2C+java&amp;#38;relative=1"&gt;this chart of Ruby job prospects.&lt;/a&gt;&lt;/p&gt;


	&lt;p&gt;Which looks like, and is, &lt;span class="caps"&gt;GREAT&lt;/span&gt; news for Rubyists, but how many have seen &lt;a href="http://www.indeed.com/jobtrends?q=ruby%2C+java"&gt;this from the same source.&lt;/a&gt; It&amp;#8217;s the same data, just looked at through a different lens.&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;m still not looking for Java work though!&lt;/p&gt;</description>
      <pubDate>Tue, 29 Jan 2008 16:24:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:29b762a2-2d17-453e-9346-48acb81d03d2</guid>
      <author>Rick DeNatale</author>
      <link>http://talklikeaduck.denhaven2.com/articles/2008/01/29/why-i-dont-mind-using-rspec-in-fact-ive-come-to-love-it</link>
      <category>ruby</category>
      <category>rails</category>
      <category>tdd</category>
      <category>bdd</category>
      <category>Rspec</category>
      <category>TestUnit</category>
      <category>TestSpec</category>
      <trackback:ping>http://talklikeaduck.denhaven2.com/articles/trackback/485</trackback:ping>
    </item>
  </channel>
</rss>
