<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' version='2.0'><channel><atom:id>tag:blogger.com,1999:blog-7618424</atom:id><lastBuildDate>Wed, 09 Dec 2009 03:09:43 +0000</lastBuildDate><title>raganwald</title><description>Never was so much owed by so many words to so few ideas.</description><link>http://weblog.raganwald.com/welcome.html</link><managingEditor>noreply@blogger.com (Reginald Braithwaite)</managingEditor><generator>Blogger</generator><openSearch:totalResults>456</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-1039201536923732175</guid><pubDate>Tue, 22 Jul 2008 14:04:00 +0000</pubDate><atom:updated>2008-09-28T19:16:04.484-04:00</atom:updated><title>A Brief History of Dangerous Ideas</title><description>&lt;font size="-1"&gt;(Brief because (a) I really don&amp;#8217;t know that much history, and (b) there&amp;#8217;s really only one idea here with a few examples, and once you get the point, we&amp;#8217;re done and can move to the outro.)&lt;/font&gt;&lt;br /&gt;&lt;br /&gt;Astronomy and Celestial Mechanics were dangerous ideas because they undermined the most powerful organization of their day, The Church. That&amp;#8217;s why people have been banned, tortured, and burned at the stake for talking about these ideas.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.cypher.net/crossbows_to_cryptography.html" title="From Crossbows to Cryptography"&gt;Crossbows&lt;/a&gt; were a dangerous idea because they allowed an untrained peasant to kill a knight. Longbows were not a dangerous idea, because only trained archers can kill a knight with a longbow, and the nobility were the only people who could compel peasants to practise yeomanry.&lt;br /&gt;&lt;br /&gt;Cryptography is not a dangerous idea, because we really don&amp;#8217;t know if any of our algorithms and protocols are resistant to the NSA. This was hi-lighted when researchers &amp;#8220;discovered&amp;#8221; differential cryptanalysis. When they looked at the &lt;a href="http://en.wikipedia.org/wiki/Data_Encryption_Standard"&gt;DES&lt;/a&gt; algorithm IBM has been promoting since the 1976, they found that it had been specifically tuned to resist differential cryptanalysis. IBM &amp;#8216;fessed up: the US government had told them to tune things that way without explaining why, leading us to conclude they had known about this attack for decades before it became public knowledge. Today, we have no idea whether what we think is strong is actually strong or whether it has vulnerabilities and back doors governments can exploit.&lt;br /&gt;&lt;br /&gt;&lt;center&gt;&lt;a href="http://www.flickr.com/photos/libinpan/2688220806/" title="Zed and Reg at Rubyfringe"&gt;&lt;img src="http://farm4.static.flickr.com/3269/2688220806_9e2a087195_m.jpg" alt="" style="border: solid 2px #000000;" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style="font-size: 0.6em; margin-top: 0px;"&gt;Zed and Reg at Rubyfringe exchanging dangerous ideas, photo by &lt;a href="http://www.flickr.com/people/libinpan/"&gt;Libin Pan&lt;/a&gt;&lt;/span&gt;&lt;/center&gt;&lt;br /&gt;Miles Davis was a walking, talking, trumpet-playing dangerous idea. Not because he reinvented Jazz five different times (Dear Steve: Apple II, Macintosh, iPod/iPhone, Pixar. One more for the tie, two for the record.) Miles was an egocentric, venal man who worked the system, not undermined the system. But he was still dangerous because he got white people directly interested in black music. There was no Elvis or Vanilla Ice or anyone else between his music and the mainstream audience. For a government intent on keeping America&amp;#8217;s two dominant cultures divided through fear, anything uniting them was a threat.&lt;br /&gt;&lt;br /&gt;People say Miles&amp;#8217; legacy is his music. To me, Miles&amp;#8217; lasting legacy is people like me, people with one parent from each culture who grew up dancing to the same music together. People who, incidentally, do not vote for governments that take a divide and conquer approach to culture.&lt;br /&gt;&lt;br /&gt;And on to tech. Microcomputers were not a dangerous idea. But &lt;em&gt;personal&lt;/em&gt; computers were dangerous. It took decades for IT departments to regain control over people bringing their own computers to work. They can thank Microsoft for helping them get back into the driver&amp;#8217;s seat.&lt;br /&gt;&lt;br /&gt;(This, incidentally, is why I really dislike Microsoft&amp;#8217;s policies: it has nothing to do with their lack of taste, it has to do with their mission to make the computer on my desk belong to my IT department or the record label or the movie studio or&amp;mdash;I suspect&amp;mdash;the government.)&lt;br /&gt;&lt;br /&gt;Web applications are dangerous. Never mind the fact that they make desktop applications obsolete. The people who built desktop applications just go and get jobs writing web applications. Same people, different shit. But as Giles Bowkett &lt;a href="http://gilesbowkett.blogspot.com/2006/12/tale-of-two-startups.html" title="Giles Bowkett: A Tale of Two Startups"&gt;pointed out&lt;/a&gt;, web applications just might make venture capital obsolete! When you don&amp;#8217;t need hundreds of programmers and distribution channels and all the other friction-managing elements of a company that ships old-school software, you need a lot less money to start a business.&lt;br /&gt;&lt;br /&gt;And on to media. You know that the web is busy putting newspapers out of business. My wife and I watched YouTube last Saturday Night. I&amp;#8217;m not talking about the advertising business: I think we would have been happy to watch ads to watch our Mitch Hedberg and Billy Connoly comedy clips. But the web lets us choose what we want to watch, when we want to watch it. The network can&amp;#8217;t put their up-and-coming show on right after their hit to give it a boost. The new show has to compete on its own merits. That puts users in control, and that&amp;#8217;s dangerous.&lt;br /&gt;&lt;br /&gt;Joel Spolsky said a similar thing about pricing all music at 99 cents a track: it means the labels can&amp;#8217;t kill an artist by sticking their CD in the $3.99 crapola bin. Users choose what they want to listen to. That&amp;#8217;s dangerous, again because users are in control.&lt;br /&gt;&lt;br /&gt;Okay, that&amp;rsquo;s enough. Dangerous ideas are the ones that subvert the existing hierarchy of control, not just the ones that shuffle people around in the same old chairs. Apple Macintosh with a GUI replacing a PC with a command line? Not dangerous. Apple Macintosh with a Laserwriter and Aldus Pagemaker allowing someone to launch a magazine in their basement that competes with a company employing dozens of layout artists? That&amp;rsquo;s dangerous, and that&amp;rsquo;s interesting.&lt;br /&gt;&lt;br /&gt;Dangerous equals subversive equals interesting.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;outro&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Deep breath. Okay, the next thing is not particularly dangerous for the world at large, but it is for me. I am retiring from blogging and retiring from hacking on Ruby. Maybe I&amp;#8217;ll un-retire one day. I don&amp;#8217;t know, the future is not set.&lt;br /&gt;&lt;br /&gt;Miles Davis wasn&amp;rsquo;t afraid to move on when the time was right, even if what he was doing seemed to make people happy. Respecting his legacy means seeking what he sought.&lt;br /&gt;&lt;br /&gt;Remember how I said that microcomputers were not dangerous, but personal computers were? Right now, I would say this: Ruby is not dangerous, but Rails is dangerous and Merb is dangerous and Sinatra is dangerous. Rewriting for Ruby is interesting. I believe it is useful. But is it &lt;em&gt;dangerous&lt;/em&gt;? No.&lt;br /&gt;&lt;br /&gt;Likewise, I can say with a clear conscience that while writing is gratifying, and trying to write out and explain ideas has helped me understand things, the writing I&amp;rsquo;ve been doing is not dangerous. It doesn&amp;rsquo;t subvert. &lt;br /&gt;&lt;br /&gt;So while hacking away on Ruby the language and blogging about software development is gratifying and useful, they are not dangerous activities. They are microcomputers, but they are not personal computers.&lt;br /&gt;&lt;br /&gt;I am going on vacation from August 2nd through 10th. During that time I plan to do absolutely no thinking about computers. For what it&amp;#8217;s worth, I will be engaging in activities with faux danger: wreck diving and sport climbing. (p.s. these are not solitary pursuits: if you want to try some of the world&amp;#8217;s greatest wreck diving and sport climbing, get in touch).&lt;br /&gt;&lt;br /&gt;When I return, I will give things some serious thought and hopefully, discover a way I can help make our world a more dangerous place.&lt;br /&gt;&lt;br /&gt;Thank you ever so much for your support and interest and feedback. Especial thanks to my fellow bloggers like Joel, Joey, Giles, Damien, Obie and so many others who exchanged ideas with me and kept the debate alive. And Reddit? And Hacker News? You rock, you are the future. I can&amp;#8217;t wait to see how your communities and technologies evolve.&lt;br /&gt;&lt;br /&gt;Warmest regards,&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Reginald Braithwaite&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-1039201536923732175?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/07/brief-history-of-dangerous-ideas.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>57</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-8915617942869161704</guid><pubDate>Tue, 22 Jul 2008 09:00:00 +0000</pubDate><atom:updated>2008-07-22T10:37:00.587-04:00</atom:updated><title>That not is not the not I meant</title><description>During &lt;a href="http://flickr.com/photos/raganwald/sets/72157606272767656/show/"&gt;my presentation at RubyFringe&lt;/a&gt;, I put this slide up while talking about &amp;ldquo;Adverbs:&amp;rdquo;&lt;br /&gt;&lt;br /&gt;&lt;center&gt;&lt;a href="http://www.flickr.com/photos/raganwald/2686915382/" title="blitz.not.blank?"&gt;&lt;img src="http://farm4.static.flickr.com/3181/2686915382_e42a8dcf9b.jpg" width="500" height="375" alt="blitz.not.blank?" /&gt;&lt;/a&gt;&lt;/center&gt;&lt;br /&gt;&lt;br /&gt;Judging by the fun we had discussing this point later, I really needed a better example or a new idea. But for thse who are a little curious about where I was trying to go with this&amp;hellip;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;more on why not is not the same as not&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;I saw the #not method somewhere, and the point was that the author felt it read better than writing &amp;ldquo;!blitz.blank?&amp;rdquo; As someone pointed out, Ruby also gives us a not keyword, so you could write &amp;ldquo;not blitz.blank?&amp;rdquo; if you prefer the word &amp;ldquo;not&amp;rdquo; to the punctuation &amp;ldquo;!&amp;rdquo;&lt;br /&gt;&lt;br /&gt;So the argument is that:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;blitz.not.blank? == !blitz.blank? # and also == (not blitz.blank?)&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;But there&amp;rsquo;s another point we&amp;rsquo;re missing comparing the word to the punctuation. Let&amp;rsquo;s switch to English and you&amp;rsquo;ll see what I mean. The sentence &amp;ldquo;It is not the case that blitz is blank&amp;rsquo; does not mean the same thing as &amp;ldquo;blitz has the property of not being blank.&amp;rdquo;&lt;br /&gt;&lt;br /&gt;Whaaaa?&lt;br /&gt;&lt;br /&gt;The key here is to think about where the parentheses go when we parse the two ways to express ourselves. Imagine &amp;ldquo;blank?&amp;rdquo; and &amp;ldquo;not&amp;rdquo; are functions instead of methods or keyword. Then two forms would look like this:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;not(blank?)(blitz) # == blitz.not.blank?&lt;br /&gt;not(blank?(blitz)) # == not blitz.blank?&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Very different. The first expression passes the blank? function to the not function. The result is another function, the inverse of blank? itself, and that&amp;rsquo;s what we use. The second form is our old not keyword, where we pass blitz to out blank function, which presumably returns true or false, and we pass the result to our not function which inverses the boolean.&lt;br /&gt;&lt;br /&gt;So in one case we are taking the inverse of a function, in the other we are taking the inverse of a boolean. This is what I was feeling out with my digression into wondering why Ruby reads from right to left. We have ways of applying functions to functions, but we don&amp;rsquo;t have easy ways of writing methods that alter other methods directly. And we certainly don&amp;rsquo;t have an easy way of sending a message that invokes such a method on an arbitrary object.&lt;br /&gt;&lt;br /&gt;I guess I wonder whether we could ever write this blitz.not(blank?) to express this idea, or perhaps blitz.(not blank?), or perhaps some other syntax. But the point would be that we want the inverse of a method, not the inverse of a boolean.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;speaking of jazz, so what?&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;It seems very abstract when we look at something like #not.blank?, because the result of an inverted #blank? method would usually be identical to the result of inverting its result.&lt;br /&gt;&lt;br /&gt;But let&amp;rsquo;s consider the case where blitz is actually a proxy for a value in a SQL database column. So you might have something like &amp;ldquo;my_model.blitz.not.blank?&amp;rdquo; Fair enough?&lt;br /&gt;&lt;br /&gt;Now if you know SQL, I think you will agree that there are times when the following is true:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;  (model1.blitz != model2.blitz) != (not model1.blitz == model2.blitz)&lt;/code&gt;&lt;/pre&gt;Although it looks like x.not.eql?(y) should always have the same semantics as not x.eql?(y), SQL has &lt;a href="http://en.wikipedia.org/wiki/Null_(SQL)"&gt;special semantics for testing NULLs&lt;/a&gt;. Specifically, NULL is neither = nor &lt;&gt; any other value. So if you carefully map your proxies to the underlying SQL behaviour, you want the above to have this behaviour.&lt;br /&gt;&lt;br /&gt;(For those who are blessed with a lack of SQL in their lives, NULL is a special value that is not the same thing as a Ruby nil. For example NULL = NULL is false in SQL. So if we map SQL values to Ruby objects, the following is the case: NULL != &lt;em&gt;anything&lt;/em&gt; is false, NULL == &lt;em&gt;anything&lt;/em&gt; is also false, therefore not NULL == &lt;em&gt;anything&lt;/em&gt; is true, and therefore (NULL != &lt;em&gt;anything&lt;/em&gt;) != (not NULL == &lt;em&gt;anything&lt;/em&gt;).&lt;br /&gt;&lt;br /&gt;If this digression into SQL NULLs now makes you regard your current ORM framework with deep suspicion, congratulations. They all suck, the trick to choosing an ORM is finding one that sucks in ways that aren&amp;rsquo;t fatal to your project.)&lt;br /&gt;&lt;br /&gt;Essentially, Ruby &lt;em&gt;already&lt;/em&gt; has a not adverb as a special case for #not==. #!= is there because sometimes (not foo == bar) is not equal to (foo != bar). However, like many things in Ruby this is a one-off thing. There isn&amp;rsquo;t a bang-method construct, #== and #!= are two completely arbitrary symbols that we happen to associate with equality and its inverse.&lt;br /&gt;&lt;br /&gt;But maybe if we had a way to derive #!= from #== using a not adverb, maybe if we could write #== and then write a #not for the method, we would be able to do interesting things like replicate SQL&amp;rsquo;s trivalent logic more accurately. We would know that foo.not &lt; 5 is not the same thing as not foo &lt; 5, because if foo is a SQL null, foo &lt; 5 is false, as is foo.not &lt; 5. And neither throws an exception!&lt;br /&gt;&lt;br /&gt;So getting back to the #not method as presented, I don&amp;rsquo;t know if it&amp;rsquo;s necessary, and if it does nothing more than replicated the exact semantics of the bang punctuation or not keyword it is clearly a matter of taste.&lt;br /&gt;&lt;br /&gt;But I do feel that there is a use case for &amp;ldquo;adverbs,&amp;rdquo; for a way to talk about modifying methods themselves. Unfortunately, right now the mechanisms for working directly with methods are somewhat arcane and thus we don&amp;rsquo;t naturally consider them. So discussions like this feel very fringe and &amp;ldquo;out there.&amp;rdquo;&lt;br /&gt;&lt;br /&gt;But at least now I feel like I have properly explained the not I meant, and not the not I didn&amp;rsquo;t mean.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-8915617942869161704?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/07/that-not-is-not-not-i-meant.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>2</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-4142227447436024458</guid><pubDate>Mon, 21 Jul 2008 16:43:00 +0000</pubDate><atom:updated>2008-07-21T14:33:12.257-04:00</atom:updated><title>"L" is not a code smell</title><description>During &lt;a href="http://flickr.com/photos/raganwald/sets/72157606272767656/show/"&gt;my presentation at RubyFringe&lt;/a&gt;, I shared a question that has been swirling around in my brain for a while: &lt;em&gt;Are IDE features really language smells?&lt;/em&gt;&lt;br /&gt;&lt;br /&gt;I don&amp;#8217;t think it&amp;#8217;s an original thought. If nothing else, it&amp;#8217;s a corollary to what I believe to be true about many of the GoF design patterns: Many of them are workarounds, ways to Greenspun missing language features. Now, this is probably not the case for all IDE features, and in truth it may be that there are some features which could be implemented in either the language or the IDE, but the IDE may be the best place to put them.&lt;br /&gt;&lt;br /&gt;But there is a fairly large class of IDE features that strike me as language workarounds. One of them is definitely the ability to spit out a lot of boilerplate. If you need a lot of code written, you ought to be able to get your programming language to do it for you, not your IDE.&lt;br /&gt;&lt;br /&gt;There is room for people to disagree about this. There are some who feel (Strawman alert!) that programs consisting of large numbers of simple elements are easier to understand than programs consisting of a small number of highly abstract elements. Those folks feel an IDE gives you the ease of writing a program quickly plus the ease of reading that same program quickly. They feel that abstractions make the program easier to write but harder to read.&lt;br /&gt;&lt;br /&gt;I happen to disagree with this, and if you have been reading this weblog for more than a couple of days you have already read why my experience leads me down a different path. Although in deference to my colleagues with different views, I offer this quote:&lt;br /&gt;&lt;br /&gt;&lt;blockquote&gt;All problems can be solved by adding another layer of abstraction, except the problem of having too many layers of abstraction.&lt;/blockquote&gt;&lt;br /&gt;Anyone who has dealt with an &lt;a href="http://discuss.joelonsoftware.com/default.asp?joel.3.219431" title="Why I Hate Frameworks"&gt;hammer factory&lt;/a&gt; will agree.&lt;br /&gt;&lt;br /&gt;So back to &amp;#8220;L.&amp;#8221;&lt;br /&gt;&lt;br /&gt;Two speakers before me, &lt;a href="http://gilesbowkett.blogspot.com/" title="Giles Bowkett"&gt;Giles Bowkett&lt;/a&gt; gave his excellent &lt;a href="http://gilesbowkett.blogspot.com/2008/02/archaeopteryx-ruby-midi-generator.html"&gt;Archaeopteryx&lt;/a&gt;&amp;#8212;um&amp;#8212;presentation. I hesitated over that word, because I could just as easily say &lt;em&gt;performance&lt;/em&gt;. Performances are terrific entertainment, but they sometimes obscure the message behind them. I want to say outright that while this is true of many other subjects, I felt it worked for Giles because the subject of his presentation was software development as a &lt;em&gt;how rather than a what&lt;/em&gt;, and for Giles the &amp;#8220;what&amp;#8221; is performance.&lt;br /&gt;&lt;br /&gt;(Giles got a standing &amp;#8220;O,&amp;#8221; and many people might be tempted to rush out and make their presentations just as stimulating (400+ in-your-face slides punctuated with loud, driving &lt;a href="http://www.youtube.com/watch?v=5SaFTm2bcac" title="The world's most important 6-sec drum loop"&gt;drum and bass&lt;/a&gt;). Be sure that your material matches your presentation style! If not, people may walk away saying &amp;#8220;Wow, amazing, but what exactly did she say?&amp;#8221; I think it worked for Giles and that&amp;#8217;s quite an accomplishment.)&lt;br /&gt;&lt;br /&gt;Now really, back to &amp;#8220;L.&amp;#8221;&lt;br /&gt;&lt;br /&gt;Giles is one of the people using closures in Ruby. Meaning, he is passing functions around and storing functions in objects. I am not going to try to say exactly what Archaeopteryx does, so I will describe this style of programming using an imaginary companion program that creates walking bass lines. I will call it &lt;a href="http://web.mit.edu/newsoffice/2001/troody-0516.html" title="AI Lab creates robotic dinosaur - MIT News Office"&gt;Troody&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Let&amp;#8217;s simplify things greatly and say that Troody will only ever play in perfect 4-4 time and further that Troody only ever play one of the eight notes in a particular chord&amp;#8217;s standard scale. The probability of playing each of those notes on any one &amp;#8220;beta&amp;#8221; could be represented as an array with eight elements, like this: [.35, .05, .1, .05, .25, .05, .1, .05 ]. You can imagine passing arrays like this around in Troody.&lt;br /&gt;&lt;br /&gt;For example, we can pass this array to an object that actually plucks the strings: Plucker.new.start_plucking([ 0.35, 0.05, 0.1, 0.05, 0.25, 0.05, 0.1, 0.05 ]).&lt;br /&gt;&lt;br /&gt;Let&amp;#8217;s try writing a na&amp;iuml;ve Troody Plucker:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;class Plucker&lt;br /&gt;    def start_plucking(probs)&lt;br /&gt;        while (self.tune.playing)&lt;br /&gt;            if (Metronone.on_the_beat)&lt;br /&gt;                r = rand&lt;br /&gt;                cumulative_probs = probs.inject([]) { |cum, element| &lt;br /&gt;                    cum + [ cum[-1] &amp;amp;&amp;amp; (cum[-1] + element) || element ] &lt;br /&gt;                }&lt;br /&gt;                notes_to_cumulative_probs = (1..8).zip(cumulative_probs)&lt;br /&gt;                note_to_play = notes_to_cumulative_probs.detect { |note, prob| prob &amp;gt;= r }&lt;br /&gt;                self.pluck(note_to_play)&lt;br /&gt;            end&lt;br /&gt;        end&lt;br /&gt;    end&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;You pass it a set of probabilities, it produces bass notes. But stop, that&amp;#8217;s so procedural. Let&amp;#8217;s learn from a flying creature, let&amp;#8217;s learn from Archaeopteryx. Instead of passing arrays, let&amp;#8217;s pass &lt;em&gt;lambdas&lt;/em&gt;, like this: lambda { [.35, .05, .1, .05, .25, .05, .1, .05 ] }. Now whenever Troody needs the probability of something, we call the function with .call or Ruby&amp;#8217;s [] alternative syntax. So now we write Plucker.new.start_plucking(lambda { [.35, .05, .1, .05, .25, .05, .1, .05 ] })&lt;br /&gt;&lt;br /&gt;Our new Plucker code is the same as the old, except we write:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;cumulative_probs = probs.call.inject([]) { |cum, element| &lt;br /&gt;    cum + [ cum[-1] &amp;amp;&amp;amp; (cum[-1] + element) || element ] &lt;br /&gt;}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;We now call the probs lambda when we need a note. That&amp;rsquo;s it, we&amp;rsquo;ve added a .call call. What does that get us? Well, here&amp;#8217;s one thing: If we want the probability to change over time, our function can do that, and we don&amp;#8217;t have to rewrite our start_plucking method to handle the idea.&lt;br /&gt;&lt;br /&gt;For example, here&amp;#8217;s a probability lambda that usually plays the same way but from time to time decides it ought to play pedal notes (refactoring to OO is an optional exercise):&lt;pre&gt;&lt;code&gt;&lt;br /&gt;probs = lambda { |bars_of_pedal, beat|&lt;br /&gt;    lambda {&lt;br /&gt;        if beat == 0&lt;br /&gt;            if bars_of_pedal == 0&lt;br /&gt;                bars_of_pedal = 1 if rand &amp;lt; .05&lt;br /&gt;            elsif bars_of_pedal == 5&lt;br /&gt;                if rand &amp;lt; .25&lt;br /&gt;                    bars_of_pedal = 0 &lt;br /&gt;                else&lt;br /&gt;                    bars_of_pedal += 1&lt;br /&gt;                end&lt;br /&gt;            elsif bars_of_pedal == 9&lt;br /&gt;                if rand &amp;lt; .5&lt;br /&gt;                    bars_of_pedal = 0 &lt;br /&gt;                else&lt;br /&gt;                    bars_of_pedal += 1&lt;br /&gt;                end&lt;br /&gt;            elsif bars_of_pedal == 13&lt;br /&gt;                bars_of_pedal = 0&lt;br /&gt;            end&lt;br /&gt;        end&lt;br /&gt;        beat = (beat + 1) % 4&lt;br /&gt;        if bars_of_pedal == 0&lt;br /&gt;            [ 0.35, 0.05, 0.1, 0.05, 0.25, 0.05, 0.1, 0.05 ]&lt;br /&gt;        else&lt;br /&gt;            [ 1.0, 0, 0, 0, 0, 0, 0, 0 ]&lt;br /&gt;        end&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}.call(0, 0)&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Thanks to the way we&amp;#8217;ve separated the probabilities from the plucking, we do not need to subclass Plucker to try a different playing style in Troody.&lt;br /&gt;&lt;br /&gt;As Giles pointed out, this is the &lt;em&gt;Strategy Pattern&lt;/em&gt;. We are making different kinds of pluckers by encapsulating the logic of what to pluck in something we pass to a plucker. Archaeopteryx appears to do this everywhere. There are lambdas paramaterized by lambdas, lambdas that return lambdas&amp;#8230;&lt;br /&gt;&lt;br /&gt;This creates a problem. Imagine a programing language where all the keywords are in upper case: IF foo THEN bar ELSE bizzat. Try reading such a program aloud, and you end up shouting the punctuation but speaking the words. This is wrong! We should be shouting the words and whispering the punctuation!&lt;br /&gt;&lt;br /&gt;And the problem with Ruby&amp;#8217;s lambdas is that if you use a lot of them the word lambda really starts to stand out. So Giles fixed this by aliasing it to L: and using [] instead of .call():&lt;pre&gt;&lt;code&gt;&lt;br /&gt;alias :L :lambda&lt;br /&gt;&lt;br /&gt;L{ |a| a + a}[5].&lt;br /&gt;    =&amp;gt; 10&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Much nicer, and as Giles pointed out, this is an example of Ruby&amp;#8217;s strength. If you have a program that rarely uses lambdas, you probably want lambdas to stand out when you use them, so you don&amp;#8217;t alias lambdas to L and you use the call method, not the square brackets. But if you use lambdas a lot, it&amp;#8217;s a win to abbreviate things.&lt;br /&gt;&lt;br /&gt;Okay, we&amp;#8217;re talking about &amp;#8220;L.&amp;#8221; Good.&lt;br /&gt;&lt;br /&gt;Now in my talk, I said that abbreviating lambda to L was a code smell. I was wrong! Giles, my bad!!&lt;br /&gt;&lt;br /&gt;What I actually think is that needing to abbreviate lambda to L is a language smell. Very different. If you show me a Java program and you show me Strategy Pattern, I shouldn&amp;#8217;t say it&amp;#8217;s a code smell. I should say too bad for you that you need all that boilerplate when Ruby lets you do that with the word lambda and a pair of curly braces.&lt;br /&gt;&lt;br /&gt;So now to &amp;#8220;L:&amp;#8221; Giles, if lambdas are integral to Archaeopteryx, if they are so woven into the fabric of what Archaeopteryx does that you want the keyword &amp;#8220;lambda&amp;#8221; to fade away, I honestly think this is a place where the language &lt;em&gt;could&lt;/em&gt; help you.&lt;br /&gt;&lt;br /&gt;For example, what if Ruby had &lt;a href="http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_name" title="Evaluation strategy - Wikipedia, the free encyclopedia"&gt;call-by-name semantics&lt;/a&gt;? You could write:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;Plucker.new.start_plucking([ 0.35, 0.05, 0.1, 0.05, 0.25, 0.05, 0.1, 0.05 ])&lt;br /&gt;&lt;br /&gt;# or...&lt;br /&gt;&lt;br /&gt;bars_of_pedal, beat = 0, 0&lt;br /&gt;Plucker.new.start_plucking(&lt;br /&gt;    if beat == 0&lt;br /&gt;        if bars_of_pedal == 0&lt;br /&gt;            bars_of_pedal = 1 if rand &amp;lt; .05&lt;br /&gt;        elsif bars_of_pedal == 5&lt;br /&gt;            if rand &amp;lt; .25&lt;br /&gt;                bars_of_pedal = 0 &lt;br /&gt;            else&lt;br /&gt;                bars_of_pedal += 1&lt;br /&gt;            end&lt;br /&gt;        elsif bars_of_pedal == 9&lt;br /&gt;            if rand &amp;lt; .5&lt;br /&gt;                bars_of_pedal = 0 &lt;br /&gt;            else&lt;br /&gt;                bars_of_pedal += 1&lt;br /&gt;            end&lt;br /&gt;        elsif bars_of_pedal == 13&lt;br /&gt;            bars_of_pedal = 0&lt;br /&gt;        end&lt;br /&gt;    end&lt;br /&gt;    beat = (beat + 1) % 4&lt;br /&gt;    if bars_of_pedal == 0&lt;br /&gt;        [ 0.35, 0.05, 0.1, 0.05, 0.25, 0.05, 0.1, 0.05 ]&lt;br /&gt;    else&lt;br /&gt;        [ 1.0, 0, 0, 0, 0, 0, 0, 0 ]&lt;br /&gt;    end&lt;br /&gt;)&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;And you would get the same behaviour as if you were using lambdas.&lt;br /&gt;&lt;br /&gt;That&amp;#8217;s it, that&amp;#8217;s what I should have said on stage: any time you are working around your language&amp;#8212;whether in your IDE, or by modifying open classes, or by abbreviating things&amp;#8212;that&amp;#8217;s a place where we should step back, where we should ask if our language is missing something.&lt;br /&gt;&lt;br /&gt;The answer may very well be &amp;#8220;no.&amp;#8221; But we ought to at least ask the question.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-4142227447436024458?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/07/l-is-not-code-smell.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>7</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-5500185377849364461</guid><pubDate>Fri, 18 Jul 2008 15:40:00 +0000</pubDate><atom:updated>2008-07-18T11:46:17.566-04:00</atom:updated><title>Raganwald on the Fringe of a Nervous Breakdown</title><description>Thanks to &lt;a href="http://www.joelonsoftware.com/items/2008/07/18.html"&gt;Joel&lt;/a&gt;, I now have a format for Sunday&amp;rsquo;s &lt;a href="http://rubyfringe.com/talks#reginald_braithewaite"&gt; presentation&lt;/a&gt; at RubyFringe: &lt;a href="http://www.wired.com/techbiz/media/magazine/15-09/st_pechakucha"&gt;Twenty slides, each on the screen for exactly twenty seconds&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-5500185377849364461?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/07/raganwald-on-fringe-of-nervous.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>2</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-915971031473597181</guid><pubDate>Thu, 17 Jul 2008 20:13:00 +0000</pubDate><atom:updated>2008-07-18T13:50:06.195-04:00</atom:updated><title>What does the word "Quality" mean?</title><description>The phrase &amp;ldquo;Quality Code&amp;rdquo; came up in a conversation with some colleagues. Just so we&amp;rsquo;re clear on what I mean when I use the word &amp;ldquo;Quality&amp;rdquo; with respect to code or architecture or software design:&lt;br /&gt;&lt;br /&gt;&lt;blockquote&gt;Quality is the antonym of &amp;ldquo;defective,&amp;rdquo; with the addition of time. Meaning, it has few known defects in its current state, &lt;em&gt;and&lt;/em&gt; we have high confidence that we will not discover defects in its current state over time, &lt;em&gt;and additionally&lt;/em&gt; that we will not create further defects in it as we add to or alter its functionality in the normal course of maintaining this software.&lt;/blockquote&gt;&lt;br /&gt;That&amp;rsquo;s a lot of blather suggesting that quality in a code base is all about making code that works as expected. Some code is designed to be extremely flexible or malleable to make it easier to add functionality in the future. This is an admirable property of a code base, however I do not think of that as affecting a code base&amp;rsquo;s quality except for the fact that a more flexible code base does sometimes allow adding functionality with a lower probability of introducing new bugs or regressions.&lt;br /&gt;&lt;br /&gt;I am not attempting to sum up all of the desirable properties of a code base. For example, in some business circumstances, increasing velocity of development at the expense of quality is a good trade-off, such as when putting together a demo that wins a large piece of business or when creating prototypes that users can use to hone a design.&lt;br /&gt;&lt;br /&gt;But when I talk about code having very high quality I mean that it has few defects and that I expect it to continue to have few defects over time. Code that is extremely brittle and highly coupled is not of high quality because I expect that any attempt to make changes will introduce regressions.&lt;br /&gt;&lt;br /&gt;Thus, the word &amp;ldquo;Quality&amp;rdquo; is not a subjective, aesthetic judgment. It is an objective measure of one axis of value to its owners.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-915971031473597181?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/07/what-does-word-quality-mean.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>7</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-6879685763213630090</guid><pubDate>Mon, 14 Jul 2008 18:45:00 +0000</pubDate><atom:updated>2008-07-14T14:57:22.411-04:00</atom:updated><title>Ruby.rewrite(Ruby) in Ten... Nine... Eight... Seven Days...</title><description>Checking the &lt;a href="http://rubyfringe.com/schedule"&gt;RubyFringe schedule&lt;/a&gt;, I see I must somehow keep the audience from yawning for thirty minutes between 2:10 and 2:40 on Sunday afternoon. I have the unenviable task of appearing between two incredibly smart and hardworking people, &lt;a href="http://rubyfringe.com/talks#damien_katz" title="CouchDB and Me"&gt;Damien Katz&lt;/a&gt; and &lt;a href="http://rubyfringe.com/talks#chris_wanstrath" title="The future is here. It's just not evenly distributed yet"&gt;Chris Wanstrath&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Upon reflection, I think I&amp;rsquo;d better open my talk with this quote from &lt;a href="http://www.imdb.com/title/tt0023027/quotes"&gt;Horse Feathers&lt;/a&gt;:&lt;br /&gt;&lt;br /&gt;&lt;blockquote&gt;I&amp;rsquo;ve got to stay here, but there&amp;rsquo;s no reason why you folks shouldn&amp;rsquo;t go out into the lobby until this thing to blows over.&lt;/blockquote&gt;&lt;div&gt;&amp;mdash;Groucho Marx&lt;/div&gt;See you at RubyFringe!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-6879685763213630090?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/07/rubyrewriteruby-in-ten-nine-eight-seven.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>3</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-3039126754144919474</guid><pubDate>Sun, 13 Jul 2008 13:45:00 +0000</pubDate><atom:updated>2008-07-13T10:52:13.631-04:00</atom:updated><title>My analyst warned me, but metaprogramming was so beautiful I got another analyst</title><description>&lt;blockquote&gt;Try to imagine a world where every programmer you know is a wannabe language designer, bent on molding the language to their whims. When I close my eyes and imagine it, I have a vision of the apocalypse, a perfect, pitch-black storm of utterly incomprehensible, pathologically difficult to debug code.&lt;/blockquote&gt;&lt;div&gt;&amp;mdash;&lt;a href="http://www.codinghorror.com/blog/archives/001151.html"&gt;Jeff Atwood&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Whereas &lt;em&gt;I&lt;/em&gt; have a vision of a world not too much different than the one we live in today. A few people invent ridiculous things, incomprehensible things. Most people carry on doing what they&amp;rsquo;ve always done. And a few people invent new, worthwhile things that move us forward.&lt;br /&gt;&lt;br /&gt;In my world, a few people inventing great things more than makes up for a few other people inventing ridiculous things. If we get Rails out of the deal, isn&amp;rsquo;t it worth giving &lt;a href="http://ick.rubyforge.org"&gt;Ick&lt;/a&gt; a bemused smile, tousling the creator&amp;rsquo;s hair and encouraging him to &amp;ldquo;keep trying?&amp;rdquo;&lt;br /&gt;&lt;br /&gt;Jeff goes on to put some smart people on a pedestal, prostrating before their greatness. I admire them as well, but I don&amp;rsquo;t confer a priesthood upon them. Once upon a time, reading and writing was not something plebeians did. Even the bible was a closed book, you only heard what was recited in Church.&lt;br /&gt;&lt;br /&gt;Does anyone doubt that democratizing the written word&amp;mdash;through education and especially Gutenberg&amp;rsquo;s invention&amp;mdash;has been a force for good?&lt;br /&gt;&lt;br /&gt;&lt;center&gt;&lt;object width="425" height="344"&gt;&lt;param name="movie" value="http://www.youtube.com/v/kwPvYZhe-yQ&amp;hl=en&amp;fs=1"&gt;&lt;/param&gt;&lt;param name="allowFullScreen" value="true"&gt;&lt;/param&gt;&lt;embed src="http://www.youtube.com/v/kwPvYZhe-yQ&amp;hl=en&amp;fs=1" type="application/x-shockwave-flash" allowfullscreen="true" width="425" height="344"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;/center&gt;&lt;br /&gt;I imagine that if we traveled back in time we would find monks bewailing what would happen if anyone was allowed to write. People&amp;mdash;the monks would stammer&amp;mdash;people might write doggerel! Pornography!! Graffiti!!!&lt;br /&gt;&lt;br /&gt;But of course, they will also write beautiful things. And useful things. Like theories of Astronomy that violate what the priests &amp;ldquo;knew&amp;rdquo; to be true. And that is the point: if you leave things up to the priesthood, all you get is stuff that is neatly aligned with what they already know. You cannot make progress by subjecting new ideas to scrutiny in a committee, even a smart and well-educated committee. Maybe &lt;em&gt;especially not&lt;/em&gt; a smart and well-educated committee.&lt;br /&gt;&lt;br /&gt;If it were up to educated people, do you think there would be personal computers today?&lt;br /&gt;&lt;br /&gt;Language design in programming is the same thing. Yes, it creates an opportunity for misunderstanding. Yes, you can make an amazing amount of trouble for yourself and for others. But to put it under lock and key in the Church where only  the priest are permitted to mention it in hushed tones&amp;hellip; this is &lt;em&gt;wrong&lt;/em&gt;.&lt;br /&gt;&lt;br /&gt;The message is clear: You and I are worker ants. We do not think. We do not question our tools. We simply use them as we are directed by those in control. I find &lt;em&gt;that&lt;/em&gt; far more horrifying than just about anything else I can imagine coming out of giving people more freedom.&lt;br /&gt;&lt;br /&gt;Come on. Really. Let&amp;rsquo;s get ahold of ourselves. As a &lt;a href="http://www.imdb.com/title/tt0079522/" title="Manhattan"&gt;wonderful movie&amp;rsquo;s&lt;/a&gt; last line went:&lt;br /&gt;&lt;br /&gt;&amp;ldquo;You have to have a little faith in people.&amp;rdquo;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-3039126754144919474?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/07/my-analyst-warned-me-but.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>20</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-2658606354140710416</guid><pubDate>Sat, 12 Jul 2008 02:47:00 +0000</pubDate><atom:updated>2008-07-13T00:37:19.439-04:00</atom:updated><title>I've seen things you people wouldn't believe</title><description>Pete Forde of &lt;a href="http://www.unspace.ca/" title="Unspace"&gt;Unspace&lt;/a&gt; emailed to say that the very first time he tried &lt;a href="http://weblog.raganwald.com/2008/01/objectandand-objectme-in-ruby.html" title="Object#andand &amp;amp; Object#me in Ruby"&gt;andand&lt;/a&gt;, he discovered a bug:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;nil&lt;br /&gt;  =&amp;gt; nil&lt;br /&gt;nil.present?&lt;br /&gt;  =&amp;gt; false&lt;br /&gt;nil.andand.present?&lt;br /&gt;  =&amp;gt; true&lt;/code&gt;&lt;/pre&gt;Reg: &lt;em&gt;Embarrassing&lt;/em&gt;.&lt;br /&gt;&lt;br /&gt;Pete: &lt;em&gt;No sir. Not embarrassing, because no one&amp;#8217;s ever going to find out they&amp;#8217;re down here. Because you&amp;#8217;re going to spot them, and you&amp;#8217;re going to air them out&lt;/em&gt;.&lt;br /&gt;&lt;br /&gt;#present? is defined in Edge Rails as:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;class Object&lt;br /&gt;    def present?&lt;br /&gt;        !blank?&lt;br /&gt;    end&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;#blank? is also defined in Rails in Object, String, and NilClass. Hmmm. It didn&amp;#8217;t take long to figure out what was happening. Internally, andand uses a &lt;a href="http://onestepback.org/index.cgi/Tech/Ruby/BlankSlate.rdoc" title="Starting with a Blank Slate"&gt;BlankSlate&lt;/a&gt; class to implement proxies for returning nil or for forwarding a method.&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;module AndAnd&lt;br /&gt;&lt;br /&gt;    class BlankSlate&lt;br /&gt;        instance_methods.each { |m| undef_method m unless m =~ /^__/ }&lt;br /&gt;        def initialize(me)&lt;br /&gt;          @me = me&lt;br /&gt;        end&lt;br /&gt;    end&lt;br /&gt;&lt;br /&gt;    class MockReturningMe &amp;lt; BlankSlate&lt;br /&gt;        def method_missing(*args)&lt;br /&gt;            @me&lt;br /&gt;        end&lt;br /&gt;    end&lt;br /&gt;&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;When you write nil.andand.present? What happens is this: nil.andand returns MockReturningMe.new(nil), and that object returns nil whenever you send it a method it doesn&amp;#8217;t understand. Since it inherits from BlankSlate, we don&amp;#8217;t expect it to understand #present?, so we expect it to return nil.&lt;br /&gt;&lt;br /&gt;(Before you ask, nil.nil? returns true, but nil.andand.nil? returns nil. That&amp;#8217;s intentional, because nil &amp;amp;&amp;amp; nil.nil? returns nil, not true.)&lt;br /&gt;&lt;br /&gt;So back to the bug. The BlankSlate wipes all of its instance methods out when it is first initialized. But what happens if the #present? method is added to Object &lt;em&gt;after&lt;/em&gt; andand initializes its BlankSlate? Ta da! The MockReturningMe class &lt;em&gt;does&lt;/em&gt; handle the method, so it never gets to use its method_missing magic.&lt;br /&gt;&lt;br /&gt;And as it happens, a MockReturningMe object is not nil, therefore it is not blank, therefore it is present and #present? returns true.&lt;br /&gt;&lt;br /&gt;If, that is, #present? is added to Object after AndAnd::BlankSlate is created. If #present? is added to Object &lt;em&gt;before&lt;/em&gt; AndAnd::BlankSlate, you get entirely different behaviour. WTF&amp;#8253;&lt;br /&gt;&lt;br /&gt;I&amp;#8217;m stating facts here, not rendering judgement: This is another example of multiple metaprogramming whatsis doohickeys all gleefully re-plumbing the same core classes and stepping on each other&amp;#8217;s toes. &lt;em&gt;Even when they aren&amp;#8217;t redefining the same methods&lt;/em&gt;.&lt;br /&gt;&lt;br /&gt;Reg: &lt;em&gt;It seems you feel our work is not a benefit to the public&lt;/em&gt;.&lt;br /&gt;&lt;br /&gt;Avdi: &lt;em&gt;Replicants are like any other machine. They&amp;#8217;re either a benefit or a &lt;a href="http://avdi.org/devblog/2008/02/23/why-monkeypatching-is-destroying-ruby/" title="Monkeypatching is Destroying Ruby"&gt;hazard&lt;/a&gt;. If they&amp;#8217;re a benefit, it&amp;#8217;s not my problem&lt;/em&gt;.&lt;br /&gt;&lt;br /&gt;&lt;em&gt;Update&lt;/em&gt;: Coderrr pointed out that the version of BlankSlate included in Rails (amongst other gems) fixes the problem by hooking the Object class. There are some subtleties in how this works or does not work, especially when several different pieces of code are all hooking the same events. After discussion with Nathan Weizenbaum, I decided that I certainly didn&amp;rsquo;t want andand being that invasive, but on the other hand if you have already decided you can live with a BlankSlate class&amp;hellip;&lt;br /&gt;&lt;br /&gt;So version 1.3.1 works as follows: If you already have a BlankSlate class defined, such as if you have installed Rails and used BlankSlate, or if you explicitly require BlankSlate before you require andand, andand will make use of the existing class and whatever mechanism that class uses to avoid this problem.&lt;br /&gt;&lt;br /&gt;If you don&amp;rsquo;t have a BlankSlate class defined but you do have a BasicObject class (such as from Ruby Facets), andand will use that instead. And if you have neither a BlankSlate nor a BasicObject, andand will roll its own fairly uninvasive BlankSlate that wipes instance methods when it is instantiated (this is a performance hit compared to wiping them when they are created, however no hooks are required).&lt;br /&gt;&lt;br /&gt;Pete is now happy. But this really encourages me to redouble my efforts on &lt;a href="http://rewrite.rubyforge.org"&gt;rewrite&lt;/a&gt;. Opening core classes to add certain kinds of functionality is very cool. But I believe it is unsustainable.&lt;br /&gt;&lt;br /&gt;Methods like #present?, #andand, and even #nil? really don&amp;#8217;t seem to work as polymorphic methods on objects. They need to be deeper. For example, you can define your own class where #nil? return true:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;class Nullo&lt;br /&gt;    def nil?&lt;br /&gt;        true&lt;br /&gt;    end&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;But guess what? This makes little sense in Ruby because your Nullo class is still truthy. (And no, you cannot write class Nullo &amp;lt; NilClass.)&lt;br /&gt;&lt;br /&gt;I&amp;#8217;ve been kvetching a little lately about Ruby not being turtles all the way down. I guess I&amp;#8217;m doing that here as well: it is very hard to write things that extend or modify Ruby&amp;#8217;s semantics consistently and safely, which i why I&amp;#8217;m looking at rewriting.&lt;br /&gt;&lt;br /&gt;With rewrite, for example, both #present? and #andand can be expressed as rewrite rules rather than as methods. (#blank? is a little bit more complicated, since you may want the luxury of writing a #blank? method for your own classes.) When you build semantic abstractions our of rewrite rules instead of methods in core classes, you benefit from restricted scope and you benefit from being able to work directly with Ruby&amp;#8217;s existing semantics.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-2658606354140710416?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/07/ive-seen-things-you-people-wouldnt.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>10</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-2024007635251108422</guid><pubDate>Tue, 08 Jul 2008 16:30:00 +0000</pubDate><atom:updated>2008-07-08T12:39:23.993-04:00</atom:updated><title>Off topic: Antagonyms</title><description>An &lt;span style="font-style:italic;"&gt;antagonym&lt;/span&gt; (also called a &lt;span style="font-style:italic;"&gt;contranym&lt;/span&gt;) is&lt;a href="http://www-personal.umich.edu/~cellis/antagonym.html"&gt; a single word that has meanings that contradict each other&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;For example, &amp;ldquo;Reg Braithwaite buckled his belt and lifted, hoping he wouldn&amp;rsquo;t buckle under the strain.&amp;rdquo; The word &amp;ldquo;buckle&amp;rdquo; has two entirely opposite meanings.&lt;br /&gt;&lt;br /&gt;Antagonyms aren&amp;rsquo;t nearly as important to the world as finding a way to make our avocation our vocation, but all the same the very idea brings a pleasant smile to my face, and I hope you&amp;rsquo;re amused as well.&lt;br /&gt;&lt;br /&gt;(via &lt;a href="http://news.ycombinator.com/item?id=239846"&gt;Hacker News&lt;/a&gt;)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-2024007635251108422?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/07/off-topic-antagonyms.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>9</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-7377687769282712835</guid><pubDate>Mon, 07 Jul 2008 11:45:00 +0000</pubDate><atom:updated>2008-07-07T17:23:37.507-04:00</atom:updated><title>Separating the concern of "what to do" from "how to do it quickly"</title><description>Over the week-end, I put together a rudimentary &lt;a href="http://weblog.raganwald.com/2008/07/sneak-peek-unhygienic-rewriting-ruby-by.html" title="Sneak Peek: Unhygienic Rewriting Ruby by Example"&gt;rewrite-by-example&lt;/a&gt; feature for the rewrite gem (please be patient, I won&amp;#8217;t be adding this feature to the gem until it has gone through a few more design iterations). The first thing I tried to do with it was simulating &lt;a href="http://en.wikipedia.org/wiki/Hygienic_macro" title="Hygienic macro - Wikipedia, the free encyclopedia"&gt;unhygienic macros&lt;/a&gt;:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;Unhygienic.from {&lt;br /&gt;&lt;br /&gt;    __to_receiver.andand.__to_message(__splat_parameters)&lt;br /&gt;&lt;br /&gt;}.to {&lt;br /&gt;&lt;br /&gt;    lambda { |andand_temp|&lt;br /&gt;      andand_temp.__to_message(__splat_parameters) if andand_temp&lt;br /&gt;    }.call(__to_receiver)&lt;br /&gt;&lt;br /&gt;}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;What this code produces is a sexp-rewriter that does a global search-and-replace. It looks for code like this:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;Person.find(:first, ...).andand.friends(true)&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;And replaces it inline with:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;lambda { |andand_temp|&lt;br /&gt;    andand_temp.friends(true) if andand_temp&lt;br /&gt;}.call(Person.find(:first, ...))&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Declarative rewriting by example is a darn sight better than hand-written sexp manipulation:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;def process_call(exp)&lt;br /&gt;  exp.shift&lt;br /&gt;  receiver_sexp = exp.first&lt;br /&gt;  if matches_andand_invocation(receiver_sexp)&lt;br /&gt;    exp.shift&lt;br /&gt;    mono_parameter = Rewrite.gensym()&lt;br /&gt;    s(:call, &lt;br /&gt;      s(:iter, &lt;br /&gt;        s(:fcall, :lambda), &lt;br /&gt;        s(:dasgn_curr, mono_parameter), &lt;br /&gt;        s(:if, &lt;br /&gt;          s(:call, s(:dvar, mono_parameter), :nil?), &lt;br /&gt;          s(:nil), &lt;br /&gt;          begin&lt;br /&gt;            s(:call, &lt;br /&gt;              s(:dvar, mono_parameter), &lt;br /&gt;              *(exp.map { |inner| process_inner_expr inner })&lt;br /&gt;            )&lt;br /&gt;          ensure&lt;br /&gt;            exp.clear&lt;br /&gt;          end&lt;br /&gt;        )&lt;br /&gt;      ), &lt;br /&gt;      :call, &lt;br /&gt;      s(:array, &lt;br /&gt;        process_inner_expr(receiver_sexp[1])&lt;br /&gt;      )&lt;br /&gt;    )&lt;br /&gt;  else&lt;br /&gt;    begin&lt;br /&gt;      s(:call,&lt;br /&gt;        *(exp.map { |inner| process_inner_expr inner })&lt;br /&gt;      )&lt;br /&gt;    ensure&lt;br /&gt;      exp.clear&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;But back to rewriting by example:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;Unhygienic.from {&lt;br /&gt;&lt;br /&gt;    __to_receiver.andand.__to_message(__splat_parameters)&lt;br /&gt;&lt;br /&gt;}.to {&lt;br /&gt;&lt;br /&gt;    lambda { |andand_temp|&lt;br /&gt;      andand_temp.__to_message(__splat_parameters) if andand_temp&lt;br /&gt;    }.call(__to_receiver)&lt;br /&gt;&lt;br /&gt;}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt; As you can deduce, it is using some magic symbols. In the &amp;#8220;from&amp;#8221; part of the definition, &lt;em&gt;__to_receiver&lt;/em&gt; and &lt;em&gt;__to_message&lt;/em&gt; mean &amp;#8220;Match something here and name the result &lt;em&gt;receiver&lt;/em&gt; and &lt;em&gt;message&lt;/em&gt; respectively,&amp;#8221; while &lt;em&gt;__splat_parameters&lt;/em&gt; means &amp;#8220;Match a list of things here and name the result &lt;em&gt;parameters&lt;/em&gt;.&amp;#8221;&lt;br /&gt;&lt;br /&gt;In the &amp;#8220;to&amp;#8221; part of the definitions, those magic symbols insert whatever was matched in the from. This is a crude approximation of how regular expressions capture things with () and insert them with $1..$n, only there is no way to capture any arbitrary sub-pattern. You can use any names you want, as long as they have the magic prefixes &lt;em&gt;__to_&lt;/em&gt; or &lt;em&gt;__splat_&lt;/em&gt;. (Magic symbols are a blight upon all that is right and good with code, suggestions for a better way to express capturing by name gratefully solicited!)&lt;br /&gt;&lt;br /&gt;&lt;div class="book"&gt;&lt;em&gt;&lt;a href="http://www.amazon.com/gp/product/026256100X?ie=UTF8&amp;tag=raganwald001-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=026256100X"&gt;&lt;img border="0" src="http://weblog.raganwald.com/uploaded_images/seasoned_schemer.jpg"&gt;&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=raganwald001-20&amp;l=as2&amp;o=1&amp;a=026256100X" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;&lt;br /&gt;&lt;br /&gt;Speaking of select, inject, and other higher-order functions, &lt;a href="http://www.amazon.com/gp/product/026256100X?ie=UTF8&amp;tag=raganwald001-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=026256100X"&gt;The Seasoned Schemer&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=raganwald001-20&amp;l=as2&amp;o=1&amp;a=026256100X" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt; is devoted to the myriad uses of first class functions. This book is approachable and a delight to read, but the ideas are provocative and when you close the back cover you will be able to compose programs from functions in powerful new ways.&lt;br&gt;&lt;br&gt;&lt;/em&gt;&lt;/div&gt;The example above is very much like a Lisp macro. In Lisp, everything is an sexp, so of course macro invocations are sexps just as function calls are sexps. In Ruby, some things look like function calls, some things look like method invocations. In this particular case, &amp;#8220;Person.find(:first, &amp;#8230;).andand.friends(true)&amp;#8221; looks like a method invocation, but it actually behaves like a macro invocation.&lt;br /&gt;&lt;br /&gt;Although it looks like a method, the rewriter version of #andand is not polymorphic. You can&amp;#8217;t override #andand in any classes, just as you can&amp;#8217;t override other syntactic constructions like &amp;#8220;&amp;amp;&amp;amp;&amp;#8221; or &amp;#8220;!&amp;#8221;. This bothers OO purists, however I am a member of the OO radical fringe who take purity to another level, a level where &lt;a href="http://weblog.raganwald.com/2008/04/is-strictly-equivalent-to.html" title="IS-STRICTLY-EQUIVALENT-TO-A"&gt;overriding functionality is not allowed to violate Liskov Equivalence&lt;/a&gt;. &lt;br /&gt;&lt;br /&gt;(I personally do not care for the idea that something like #andand sometimes means one thing and sometimes means another, just as many people would completely freak out if !foo didn&amp;#8217;t always mean &amp;#8220;not foo.&amp;#8221;)&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;beyond macros&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Rewriting goes beyond adding new functions and verbs (I personally consider #andand to be an adverb). Basically, what we have here is an extremely weak version of XSLT for Ruby code. Match this, turn it into that. IMO, XSLT transformations is a much better analogy than macro expansion. Rewriters can match and replace fairly arbitrary expressions, not just implement things that look like function calls and method calls.&lt;br /&gt;&lt;br /&gt;Consider this hypothetical example:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;Unhygienic.from {&lt;br /&gt;&lt;br /&gt;    __to_receiver.select { |__to_x| &lt;br /&gt;        __to_select_body &lt;br /&gt;    }.inject(__to_seed) { |__to_acc, __to_y| &lt;br /&gt;        __to_inject_body&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}.to {&lt;br /&gt;&lt;br /&gt;    __to_receiver.inject(__to_seed) { |__to_acc, __to_x|&lt;br /&gt;        if __to_select_body&lt;br /&gt;            __to_y = __to_x&lt;br /&gt;            __to_inject_body&lt;br /&gt;        else&lt;br /&gt;            __to_acc&lt;br /&gt;        end&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;This would transformation code like this:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;heads_of_state = locations.select { |any_loc| &lt;br /&gt;    zips_in_this_state.include? any_loc.zip_code&lt;br /&gt;}.inject(0) { |heads, loc_in_state|&lt;br /&gt;    heads + loc_in_state.head_count&lt;br /&gt;}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Into this:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;heads_of_state = locations.inject({}) { |heads, any_loc|&lt;br /&gt;    if zips_in_this_state.include? any_loc.zip_code&lt;br /&gt;        loc_in_state = any_loc&lt;br /&gt;        heads + loc_in_state.head_count&lt;br /&gt;    else&lt;br /&gt;        heads&lt;br /&gt;    end&lt;br /&gt;}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;This is an example of an &lt;em&gt;optimization&lt;/em&gt;.&lt;br /&gt;&lt;br /&gt;For a large class of expressions chaining a select and an inject (the ones that don&amp;#8217;t rely on side effects), this transformation retains the original semantics while rewriting the code to only traverse the collection once and to eliminate the creation of an intermediate collection.&lt;br /&gt;&lt;br /&gt;Of course, compilers do this kind of thing all the time for many types of optimizations, so it&amp;#8217;s tempting to wait for someone else to write a &lt;a href="http://c2.com/cgi/wiki?SufficientlySmartCompiler" title="Sufficiently Smart Compiler"&gt;sufficiently smart compiler&lt;/a&gt; that can figure these things out. There are two troubles with waiting for someone else to do it. First, we might be that someone&amp;#8212;maybe we&amp;#8217;re the one who ought to Just Do It, and waiting for someone else won&amp;#8217;t work because nobody else is going to do it.&lt;br /&gt;&lt;br /&gt;Second, many problems like this are intractable in the general case. It&amp;#8217;s hard (in the mathematical sense) to know when select {&amp;#8230;. }.inject { &amp;#8230; } can be transformed like this in an imperative language without accidentally stepping on some hidden side-effect. But just because it&amp;#8217;s hard in the general case doesn&amp;#8217;t mean it isn&amp;#8217;t easy in the specific case. For example, you might be the sort of person who &lt;em&gt;never&lt;/em&gt; knowingly relies on side effects in select and inject expressions.&lt;br /&gt;&lt;br /&gt;So &lt;em&gt;you&lt;/em&gt; could use this optimization, while a compiler-level optimization would be a disaster: even if 99.9% of the code out there wouldn&amp;#8217;t break, the programmers behind the 0.1% of the broken programs would be furiously blogging about how Ruby wasn&amp;#8217;t ready for the Enterprise.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;optimizing your code&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;The joy and the pain of optimizing your code is that you don&amp;#8217;t need rewrite to perform that optimization. The joy is that if you discover chaining select and inject is a performance hog somewhere in your code, you simply rewrite the code yourself.&lt;br /&gt;&lt;br /&gt;The pain is that the code is no longer in the form you originally decided best represents its intent. In the trivial example I gave above, a rewritten version looks reasonable, especially if you rewrite it with #each in an imperative style:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;heads_of_state = 0&lt;br /&gt;locations.each { |any_loc|&lt;br /&gt;    if zips_in_this_state.include? any_loc.zip_code&lt;br /&gt;        heads_of_state += any_loc.head_count&lt;br /&gt;    end&lt;br /&gt;}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Now I&amp;#8217;m not going to say that this is necessarily more or less readable than:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;heads_of_state = locations.select { |any_loc| &lt;br /&gt;    zips_in_this_state.include? any_loc.zip_code&lt;br /&gt;}.inject(0) { |heads, loc_in_state|&lt;br /&gt;    heads + loc_in_state.head_count&lt;br /&gt;}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Some people actively dislike using #select and #inject, so they might feel the #each version is better. For once, let&amp;#8217;s talk about something other than a &lt;a href="http://en.wikipedia.org/wiki/Color_of_the_bikeshed" title="Color of the bikeshed - Wikipedia, the free encyclopedia"&gt;bike shed&lt;/a&gt;. Let&amp;#8217;s focus on the fact that foo.select {&amp;#8230;}.inject {&amp;#8230;} says one thing: &amp;#8220;Filter this collection using this predicate, and then fold the result as follows.&amp;#8221; Whereas foo.each {&amp;#8230;} says &amp;#8220;Iterate over this collection doing the following thing with each element.&amp;#8221;&lt;br /&gt;&lt;br /&gt;If you wrote this as a #select/#inject pair, you might have a good reason for doing so. Perhaps most of your program is written in a functional style. Perhaps you like to signal that the there are no side effects in those snippets of code and your team share this understanding of how selects and injects are written.&lt;br /&gt;&lt;br /&gt;Granting that you believe that #select and #inject do a better job of communicating the code&amp;#8217;s intent to your fellow team members, it&amp;#8217;s a win to optimize the code (in the compiler or using a rewriter) behind the scenes rather than rewrite it yourself. The code retains its semantics and the form you have decided best expresses its intent, while using less memory and running faster.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;separation of concerns&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;What we have just done with our trivial example is separated two concerns: The concerns of how to best express an algorithm and the concern of how to best implement an algorithm. If for whatever reason&amp;#8212;furious hand-waving to avoid arguing how to write loops&amp;#8212;we believe that the best way to express a certain algorithm for readability is not the best way to express a certain algorithm for performance, we have two separate concerns: How to write readable code and how to write &lt;strike&gt;performant&lt;/strike&gt; fast code.&lt;br /&gt;&lt;br /&gt;Doesn&amp;#8217;t it make sense to separate those concerns? So that the code explaining what the algorithm is supposed to do is in one place and the code expressing how to make such things go fast is in another?&lt;br /&gt;&lt;br /&gt;This is pure speculation here, but I am conjecturing that being able to rewrite arbitrary snippets of code could be used like a compiler optimization directive. When debugging, you don&amp;#8217;t rewrite the code. But when things have stabilized and you need to tweak performance, instead of rewriting the code, you use rewriters to do it for you, separating the concern of &amp;ldquo;what to do&amp;rdquo; from the concern of  &amp;ldquo;how to do it quickly.&amp;rdquo;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-7377687769282712835?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/07/separating-concerns-of-what-to-do-from.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>7</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-7582180003210279442</guid><pubDate>Sun, 06 Jul 2008 01:59:00 +0000</pubDate><atom:updated>2008-07-05T23:06:51.655-04:00</atom:updated><title>Sneak Peek: Unhygienic Rewriting Ruby by Example</title><description>&lt;pre&gt;&lt;code&gt;&lt;br /&gt;def test_unhygienic_andand&lt;br /&gt;  andand = Unhygienic.from {&lt;br /&gt;    __to_receiver.andand.__to_message(__splat_parameters)&lt;br /&gt;  }.to {&lt;br /&gt;    lambda { |andand_temp|&lt;br /&gt;      andand_temp.__to_message(__splat_parameters) if andand_temp&lt;br /&gt;    }.call(__to_receiver)&lt;br /&gt;  }&lt;br /&gt;  assert_equal(&lt;br /&gt;    'Hello' + ' World', &lt;br /&gt;    with(andand) do&lt;br /&gt;        'Hello'.andand + ' World'&lt;br /&gt;    end&lt;br /&gt;  )&lt;br /&gt;  assert_nil(&lt;br /&gt;    with(andand) do&lt;br /&gt;        nil.andand + ' World'&lt;br /&gt;    end&lt;br /&gt;  )&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;Let&amp;rsquo;s take a closer look:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;Rewrite::With.expand(andand) do&lt;br /&gt;  class Funky&lt;br /&gt;    def hello_world&lt;br /&gt;      'Hello'.andand + ' World'&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;produces:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;class Funky&lt;br /&gt;  def hello_world&lt;br /&gt;    lambda { |andand_temp| &lt;br /&gt;        (andand_temp + " World") if andand_temp &lt;br /&gt;    }.call("Hello")&lt;br /&gt;  end&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;As you can probably deduce, it&amp;rsquo;s &lt;a href="http://en.wikipedia.org/wiki/Hygienic_macro" title="Hygienic Macros"&gt;unhygienic&lt;/a&gt;: Variables like andand_temp shadow variables declared elsewhere. This is a problem if you fail to choose a sufficiently obfuscated name or&amp;mdash;more likely&amp;mdash;nest constructions like #andand.&lt;br /&gt;&lt;br /&gt;Both the &lt;a href="http://andand.rubyforge.org/" title="andand.rubyforge.org"&gt;Classically Metaprogrammed&lt;/a&gt; and the &lt;a href="http://weblog.raganwald.com/2008/06/not-going-dark.html" title="Not going dark"&gt;Sexp-Rewriting&lt;/a&gt; versions of #andand avoid this problem.&lt;br /&gt;&lt;br /&gt;Next step: Better hygiene.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-7582180003210279442?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/07/sneak-peek-unhygienic-rewriting-ruby-by.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-7069701310959514085</guid><pubDate>Wed, 02 Jul 2008 20:00:00 +0000</pubDate><atom:updated>2008-07-02T16:25:23.885-04:00</atom:updated><title>Process Theatre</title><description>You know how Bruce Schneier uses the term &lt;a href="http://en.wikipedia.org/wiki/Security_theater"&gt;Security Theatre&lt;/a&gt; to describe &lt;a href="http://www.schneier.com/blog/archives/2006/08/terrorism_secur.html"&gt;measures designed to make us feel safer but not actually safer&lt;/a&gt;? I am going to start using the term &lt;em&gt;Process Theatre&lt;/em&gt;. I trust you can grasp the meaning immediately.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-7069701310959514085?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/07/process-theatre.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>1</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-7913495048534768878</guid><pubDate>Tue, 01 Jul 2008 23:42:00 +0000</pubDate><atom:updated>2008-07-01T20:12:21.612-04:00</atom:updated><title>A blatant exercise in pimping an affiliate link to Art of the Metaobject Protocol</title><description>&lt;blockquote&gt;&lt;a href="http://www.amazon.com/gp/product/0262610744?ie=UTF8&amp;tag=raganwald001-20&amp;link_code=as3&amp;camp=211189&amp;creative=373489&amp;creativeASIN=0262610744"&gt;The Art of the Metaobject Protocol&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=raganwald001-20&amp;amp;l=as2&amp;amp;o=1&amp;amp;a=0262610744" alt="" style="border: medium none  ! important; margin: 0px ! important;" border="0" height="1" width="1"&gt; is the best book written in computing in ten years.&lt;/blockquote&gt;&lt;div&gt;&amp;mdash;Alan Kay, as quoted in &lt;a href="http://www-static.cc.gatech.edu/fac/mark.guzdial/squeak/oopsla.htm"&gt;Report on OOPSLA97&lt;/a&gt;&lt;/div&gt;&lt;p&gt;The bottom line: Languages like Java give you an object protocol: There is one way to do things with objects and classes and interfaces, period. Anything else, like adding generics or annotations, must be done outside of the language, it must be done by the creators of the language.&lt;/p&gt;&lt;p&gt;Languages like Common Lisp and Smalltalk give you a &lt;em&gt;meta&lt;/em&gt; object protocol: You can decide for yourself how to do things with objects, classes, interfaces, generic functions, whatever you want. You don&amp;rsquo;t need to wait for a committee to try something different.&lt;/p&gt;&lt;p&gt;People who believe that software is best created in a Soviet-era Bureaucracy celebrating process and mediocrity&amp;mdash;all the while spouting propaganda about celebrating the common worker and the primacy of the proletariat, of course&amp;mdash;fear and loathe this idea. They will tell you that standardization trumps innovation, and that the only thing worse than metaprogramming within a standard object system is metaprogramming the system itself.&lt;/p&gt;&lt;p&gt;But we saw how valuing process over people played out, and our minds are actually open to new ideas, even when those ideas are forty years old.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-7913495048534768878?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/07/blatant-exercise-in-pimping-affiliate.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>5</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-3851212997327201496</guid><pubDate>Mon, 30 Jun 2008 14:42:00 +0000</pubDate><atom:updated>2008-06-30T12:10:14.195-04:00</atom:updated><title>My Mixed Feelings about Ruby</title><description>&lt;blockquote&gt;There&amp;#8217;s a lot of features of Ruby that I like, but there are some that just drive me nuts like blocks not taking blocks and the ampersand operator. Raganwald did a great job of explaining blocks, procs, and the ampersand in this blog post: &lt;a href="http://weblog.raganwald.com/2008/06/what-does-do-when-used-as-unary.html"&gt;Explanation of Ruby&amp;#8217;s Unary operator&lt;/a&gt;. I came away with the feeling, &amp;#8220;Wow! It took that much explanation just to tell how to send blocks around?&amp;#8221; If blocks were first-class citizens, Ruby would be more elegant. Raganwald would not be writing huge blog posts on block vs. proc because it would be unneeded.&lt;/blockquote&gt;&lt;div&gt;&amp;mdash;Blaine Buxton, &lt;a href="http://blog.blainebuxton.com/2008/06/too-complex.html"&gt;Too Complex?&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;I feel for Blaine, I really do. When I first looked at Ruby, quite honestly I hated it. Not hated it in a Blubb-dacious &amp;ldquo;It&amp;rsquo;s not the same as my popular language&amp;rdquo; way, but hated it in a &amp;ldquo;The language is full of Accidental Complexity&amp;rdquo; way.&lt;br /&gt;&lt;br /&gt;To my eyes, Ruby as a language looked a lot like an internal IT app that is built as an aggregation of features. There might be a wonderful, coherent design in the implementation that I can&amp;rsquo;t see, but the interface I use seems like a bunch on one-off features that don&amp;rsquo;t play well together.&lt;br /&gt;&lt;br /&gt;Ruby definitely isn&amp;rsquo;t &lt;a href="http://www.cincomsmalltalk.com/userblogs/avi/blogView?showComments=true&amp;entry=3284695382"&gt;turtles all the way down&lt;/a&gt;. And I have never stopped being troubled by this. I lamented the fact that &lt;a title="The significance of the meta-circular interpreter" href="http://weblog.raganwald.com/2006/11/significance-of-meta-circular_22.html"&gt;Ruby isn&amp;rsquo;t written in Ruby&lt;/a&gt;. &lt;a title="Why Rubinius Matters to Ruby's Future" href="http://weblog.raganwald.com/2007/12/why-rubinius-matters-to-rubys-future.html"&gt;Twice&lt;/a&gt;. No, make that &lt;a title=" Turtles all the way down, please" href="http://weblog.raganwald.com/2008/02/turtles-all-way-down-please.html"&gt;three times&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Deep breath. But.&lt;br /&gt;&lt;br /&gt;There&amp;rsquo;s a part of my personality that craves purity and regularity in a system. Purity and regularity have practical benefits, to be sure, but at the same time there are practical benefits to being messy and having special cases optimizing for things people do frequently. This is why design is freakin&amp;rsquo; hard. It&amp;rsquo;s not as easy as following a bunch of rules that produce a system with the smallest possible intellectual surface area, otherwise we&amp;rsquo;d have stopped with Scheme and its five axiomatic special forms.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;center&gt;&lt;object width="425" height="344"&gt;&lt;param name="movie" value="http://www.youtube.com/v/1kvdq8cRNBM&amp;hl=en"&gt;&lt;/param&gt;&lt;embed src="http://www.youtube.com/v/1kvdq8cRNBM&amp;hl=en" type="application/x-shockwave-flash" width="425" height="344"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;A Rube Goldberg contraption does a simple thing (like making ramen) in an extremely complex way. It turns accidental complexity and irregularity into entertainment.&lt;/em&gt;&lt;/center&gt;&lt;br /&gt;Nor is it as easy as piling more features on regardless of how well they fit or whether people will actually use them. Otherwise Windows would have 97% of the market and OS X 3%. (&lt;em&gt;Oh wait&lt;/em&gt;.)&lt;br /&gt;&lt;br /&gt;When it comes to design, sometimes you have to experience the result to judge it. You can decide whether a chair is attractive by looking at it, but you really need to sit in it a while to know whether you will feel comfortable using it. Even then, only long experience will tell you whether it is a keeper. Many things that are nice in the showroom are mediocre in day-to-day use.&lt;br /&gt;&lt;br /&gt;Design is all about problem solving. What problem do you think programming languages solve as a group? What problem does Lisp solve? Smalltalk? Ruby? For whom?&lt;br /&gt;&lt;br /&gt;Matz has said that Ruby is an attempt to solve the problem of making programmers happy. So maybe we aren&amp;rsquo;t happy with some of the accidental complexity. But can we be happy overall? Can we find a way to program in harmony with Ruby rather than trying to &lt;a href="http://en.wikipedia.org/wiki/Greenspun's_Tenth_Rule"&gt;Greenspun&lt;/a&gt; it into Lisp?&lt;br /&gt;&lt;br /&gt;(I speak as a man working on rewriting code for Ruby: By far the hardest part of this is trying to provide the power of macros in a mechanism that works in harmony with the Ruby Way, rather than bolting Lisp onto Ruby&amp;rsquo;s side.)&lt;br /&gt;&lt;br /&gt;Programming languages also solve the deep problem of helping programmers think about the parts of a program that matter and not clutter their minds up with the parts that don&amp;rsquo;t matter. This is a very hard problem. Very, very hard. Make things too simple, have too few axioms and abstractions, and you end up with something where each element is extremely simple to understand, but any non-trivial program has too many elements with difficult-to-understand interactions and dependencies so as a whole programs are harder to understand.&lt;br /&gt;&lt;br /&gt;Does a regular language help us understand the parts of programs that matter more than an irregular language? That is not an easy question to answer. When I&amp;rsquo;m struggling with some subtle difference between Proc.new and lambda, I want to shout YES, GODDAMIT, GIVE ME SOME CONSISTENCY.&lt;br /&gt;&lt;br /&gt;I&amp;rsquo;m wary of trying to decide about languages based on infrequent edge cases. With a certain very popular language, I&amp;rsquo;ve made up my mind that the design choices don&amp;rsquo;t pay off, that the places where you work hard to express yourself aren&amp;rsquo;t places where the easy, obvious thing is easy to write and obvious to read. But so far in Ruby, the things that trouble me do seem to have some inherent trade-off merit. I can see how making blocks a special case makes certain eay, simple things easy. So is it overall the best possible design? I don&amp;rsquo;t know. is it a good design? So far it seems to be a reasonable design.&lt;br /&gt;&lt;br /&gt;At my core, I believe axiomatically that there is no one &amp;ldquo;best&amp;rdquo; language. That is not an excuse for saying that every language has merit. While I think that there can be more than one good language with different approaches and styles, I do not exclude the possibility that 90% of the programming languages in existence are stinkers through and through.&lt;br /&gt;&lt;br /&gt;Is Ruby better for me personally than Lisp or Smalltalk? I don&amp;rsquo;t know the answer to that question either.&lt;br /&gt;&lt;br /&gt;I decided a while back that I would &lt;a title="I'm not young enough to know everything" href="http://weblog.raganwald.com/2005/10/im-not-young-enough-to-know-everything.html"&gt;give Ruby an honest try&lt;/a&gt;. And while I give myself the freedom to express my misgivings about some of the choices Matz has made, I also try to keep an open mind about them.&lt;br /&gt;&lt;br /&gt;It&amp;rsquo;s really freakin&amp;rsquo; (I know, I used this word already) hard for me to to do, but I&amp;rsquo;m trying to find out if &lt;a href="http://www.dreamsongs.com/WorseIsBetter.html"&gt;worse might be better&lt;/a&gt;. And I don&amp;rsquo;t mean, &amp;ldquo;Ruby is worse than Lisp, but it&amp;rsquo;s better for those n00bs over there.&amp;rdquo; That&amp;rsquo;s not embracing change. I mean I am trying to discover if worse might be better for me personally, and it is hard for me to open my mind to that possibility when I&amp;rsquo;m already invested in &amp;ldquo;better.&amp;rdquo;&lt;br /&gt;&lt;br /&gt;At this moment in time I have extremely mixed feelings about Ruby. I sorely miss the elegance and purity of languages like Scheme and Smalltalk. But at the same time, I am trying to keep my mind open to some of the ways in which Ruby is a great programming language.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-3851212997327201496?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/06/my-mixed-feelings-about-ruby.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>23</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-2487354129772750654</guid><pubDate>Fri, 27 Jun 2008 20:07:00 +0000</pubDate><atom:updated>2008-07-02T16:23:44.486-04:00</atom:updated><title>The unary ampersand in Ruby</title><description>&lt;p&gt;A marshmallow toasting dragon slayer from Montréal &lt;a href="http://lovehateubuntu.blogspot.com/2008/06/some-neat-things-in-ruby.html" title="Some Neat Things in Ruby"&gt;asked about the unary &amp;amp;&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;I like this question, because when I saw it, I realized immediately that although I’ve figured out how to use it to accomplish certain things, writing an answer serves the excellent purpose of forcing myself to learn more.&lt;/p&gt;&lt;p&gt;Let’s start with what I do know, and what everyone can figure out from grepping source code: &lt;em&gt;It has something to do with converting things to and from blocks&lt;/em&gt;. If you take nothing else away from this, remember that when you see a unary “&amp;amp;” in Ruby, you are looking at making something into a block, or making a block into something.&lt;/p&gt;&lt;p&gt;Now, blocks in Ruby are not first-class entities. You cannot store them in variables. They are not objects. There is no Block.new expression. The only way to make a block in Ruby syntax is to write one as part of a method call, like this:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;[1, 2, 3, 4, 5].map { |x| x * x  }&lt;br /&gt;    =&amp;gt; [1, 4, 9, 16, 25]&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As we said above, you &lt;strong&gt;cannot&lt;/strong&gt; assign a block to a variable:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;square_block = { |x| x * x  }&lt;br /&gt;    =&amp;gt; syntax error, unexpected '}', expecting $end&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;What do we do with these blocks? Well, inside of a method, we can yield to a block. Yielding to a block is something very much like calling a function. The value of an expression yielding to a block is the value of the expression in the block, paramaterized by anything you pass in the yield expression.&lt;/p&gt;&lt;p&gt;Oh heck, an example is much better:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;def take_a_guess(range) # expects a block testing a guess&lt;br /&gt;    guess = range.begin + rand(range.end - range.begin)&lt;br /&gt;    if yield(guess)&lt;br /&gt;        "Yay, I guessed correctly"&lt;br /&gt;    else&lt;br /&gt;        "Boo hoo, my guess was wrong"&lt;br /&gt;    end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;take_a_guess(1..10) { |x| x == 6 }&lt;br /&gt;    =&amp;gt; "Boo hoo, my guess was wrong"&lt;br /&gt;take_a_guess(1..10) { |x| x == 6 }&lt;br /&gt;    =&amp;gt; "Boo hoo, my guess was wrong"&lt;br /&gt;take_a_guess(1..10) { |x| x == 6 }&lt;br /&gt;    =&amp;gt; "Yay, I guessed correctly"&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This method plays a guessing game with you: it takes a range (“guess a number from one to ten”) and a block for testing whether the guess was correct. It takes a guess and yield the guess to the block. It then exclaims its joy to the world if it guesses correctly.&lt;/p&gt;&lt;p&gt;Notice that there is nothing in the method signature saying it expects a block. There is no name for the block. You have to look for the yield keyword to figure out what is going on if the programmer doesn’t add a comment.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;converting blocks to procs&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;So… Let’s talk conversions. If you want to do &lt;em&gt;anything&lt;/em&gt; besides invoke a block with yield, you really want a Proc, not a block. For example:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;class Guesser&lt;br /&gt;    attr_reader :range, :tester&lt;br /&gt;    def initialize(range, &amp;amp;tester)&lt;br /&gt;        @range, @tester = range, tester&lt;br /&gt;    end&lt;br /&gt;    def take_a_guess&lt;br /&gt;        guess = range.begin + rand(range.end - range.begin)&lt;br /&gt;        if tester.call(guess)&lt;br /&gt;            "Yay, I guessed #{guess} correctly"&lt;br /&gt;        else&lt;br /&gt;            "Boo hoo, my guess of #{guess} was wrong"&lt;br /&gt;        end&lt;br /&gt;    end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;foo = Guesser.new(1..10) { |n| n == 6 }&lt;br /&gt;foo.take_a_guess&lt;br /&gt;    =&amp;gt; "Boo hoo, my guess of 2 was wrong"&lt;br /&gt;foo.take_a_guess&lt;br /&gt;    =&amp;gt; "Boo hoo, my guess of 8 was wrong"&lt;br /&gt;foo.take_a_guess&lt;br /&gt;    =&amp;gt; "Yay, I guessed 6 correctly"&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We want to store the tester block as an instance variable. So what we do is add a parameter at the very end with an ampersand, and what Ruby does is take the block and convert it to a Proc, which you can pass around as an object. And when you want to use it, you send it the #call method.&lt;/p&gt;&lt;p&gt;Now if you think about this for a second or two, you’ll realize that almost every Proc you ever create works this way: We pass a block to a method, and the method turns it into a proc by having a parameter with an &amp;amp;. Let’s try writing another one:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;def our_proc(&amp;amp;proc)&lt;br /&gt;    proc&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;double = our_proc { |n| n * 2}&lt;br /&gt;double.call(7)&lt;br /&gt;    =&amp;gt; 14&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Not much to it, is there? When you want a Proc, you can create one by calling a method with a block and using &amp;amp;parameter to convert the block to a Proc. There is no other way to convert a block to a proc because the only place blocks exist is in method invocations.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;converting procs to blocks&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Okay, we know how to make a Proc out of a block. What about going the other way? What if we want to make a block out of a Proc?&lt;/p&gt;&lt;p&gt;Let’s reopen our Guesser class:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;class Guesser&lt;br /&gt;    def three_guesses&lt;br /&gt;        guesses = Array.new(3) { range.begin + rand(range.end - range.begin) }&lt;br /&gt;        if guesses.any?(&amp;amp;tester)&lt;br /&gt;            "Yay, #{guesses.join(', ')} includes a correct guess"&lt;br /&gt;        else&lt;br /&gt;            "Boo hoo, my guesses of #{guesses.join(', ')} were wrong"&lt;br /&gt;        end&lt;br /&gt;    end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;bar = Guesser.new(1..10) { |x| x == 3 }&lt;br /&gt;bar.three_guesses&lt;br /&gt;    =&amp;gt; "Yay, 5, 9, 3 includes a correct guess"&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;What just happened?&lt;/p&gt;&lt;p&gt;For starters, we made an array with three guesses in it. That line of code includes a block, but let’s ignore that as being irrelevant to this particular discussion. The next part is what we’re after:&lt;/p&gt;&lt;p&gt;We then want to call &lt;a href="http://www.ruby-doc.org/core/classes/Enumerable.html#M001153" title="Module: Enumerable"&gt;Enumerable#any?&lt;/a&gt; to ask the array if any of its members are the correct guess. Now #any? expects a block. But we don’t have a block, we have a Proc. So now we do the &lt;em&gt;reverse&lt;/em&gt; of what we did when we wanted to convert a block to a Proc: instead of a method having an extra parameter with an ampersand, we pass a parameter to the method and apply the ampersand to the parameter we are passing.&lt;/p&gt;&lt;p&gt;So “&amp;amp;tester” says to Ruby: “Take this object and pass it to a method as a block.” The #any? method gets a block, it has no idea we are doing any Proc to block conversion shenanigans. We can prove that:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;def did_you_pass_me_a_block?&lt;br /&gt;    if block_given?&lt;br /&gt;        yield&lt;br /&gt;    else&lt;br /&gt;        "NO BLOCK"&lt;br /&gt;    end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;did_you_pass_me_a_block?&lt;br /&gt;    =&amp;gt; "NO BLOCK"&lt;br /&gt;did_you_pass_me_a_block? { 'I passed you a block' }&lt;br /&gt;    =&amp;gt; "I passed you a block"&lt;br /&gt;proc = Proc.new { 'I passed you a proc' }&lt;br /&gt;did_you_pass_me_a_block?(&amp;amp;proc)&lt;br /&gt;    =&amp;gt; "I passed you a proc"&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;As you can see, our methods don’t really know whether they get a block or a proc passed as a block. They just yield and all is well. (And yes, you can convert a block to a proc and then the method can convert it right back into another proc.)&lt;/p&gt;&lt;p&gt;&lt;strong&gt;to_proc shakur&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Which leads us to the final piece of the puzzle. How does Ruby convert whatever you pass with “&amp;amp;” into a block? The answer is that if it is not already a Proc, it tries to convert the object to a Proc by calling the object’s #to_proc method, and from there it converts the Proc into a block.&lt;/p&gt;&lt;p&gt;So you can do fun stuff like convert strings into blocks &lt;a href="http://weblog.raganwald.com/2007/10/stringtoproc.html" title="String#to_proc"&gt;by defining a method that converts a string to a Proc&lt;/a&gt;:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;(1..5).map &amp;amp;'*2'&lt;br /&gt;    =&amp;gt; [2, 4, 6, 8, 10]&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Note that this conversion only happens when you try to pass a string as a block to a method with “&amp;amp;.” It is not correct to say that “&amp;amp;” converts an object to a Proc, the #to_proc method does that. It is correct to say that when passing an object to a method, the “&amp;amp;” unary operator tries to convert the object to a block, using the Object’s #to_proc method if need be.&lt;/p&gt;&lt;p&gt;We’ll close with an example, where we decide that a Guesser can be converted to a Proc:&lt;/p&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;class Guesser&lt;br /&gt;    def to_proc&lt;br /&gt;        Proc.new { |guess|&lt;br /&gt;            "Yay, I guessed #{guess} correctly" if tester.call(guess)&lt;br /&gt;        }&lt;br /&gt;    end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;foo = Guesser.new(1..10) { |n| n == 8 }&lt;br /&gt;&amp;amp;foo&lt;br /&gt;    =&amp;gt; syntax error, unexpected tAMPER&lt;br /&gt;foo.to_proc&lt;br /&gt;    =&amp;gt; #&amp;lt;Proc:0x0008cc08@-:26&amp;gt;&lt;br /&gt;(1..100).map(foo).compact.first&lt;br /&gt;    =&amp;gt; ArgumentError: wrong number of arguments (1 for 0)&lt;br /&gt;(1..100).map(&amp;amp;foo).compact.first&lt;br /&gt;    =&amp;gt; "Yay, I guessed 8 correctly"&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So that’s it: When you want to convert a block to a Proc, define an extra parameter for your method and preface it with an ampersand. When the method is called, the parameter will hold a proc.&lt;/p&gt;&lt;p&gt;When you want to convert any object to a block, pass it to a method expecting a block and preface it with an ampersand. Ruby will call the #to_proc method if need be, then convert the Proc into a block.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;because it’s friday&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;I really hate writing anything too serious on a Friday. So if you’re eyes have glazed over and you’ve marked this to be read later, here’s a little diversion for you. I just picked up &lt;a href="http://www.amazon.com/gp/product/8876990666?ie=UTF8&amp;amp;tag=raganwald001-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=8876990666"&gt;The Magic Garden of George B. And Other Logic Puzzles&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=raganwald001-20&amp;amp;l=as2&amp;amp;o=1&amp;amp;a=8876990666" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt; by my favourite nonfiction author, Raymond Smullyan.&lt;/p&gt;&lt;p&gt;Right off the bat, the first paragraphs of the preface introduce a neat puzzle:&lt;/p&gt;&lt;blockquote&gt;Here is a remarkable problem: Imagine a garden of magic flowers that can change color from day to day. On any one day, a flower is either blue the entire day or red the entire day, but can change from one day to another. Given any flower A and any flower B, there is a flower C that is red on all and only those days on which A and B are both blue. Also, we are given that for any distinct flowers A and B, there is at least one day on which A and B are of different colors. Now suppose that the number of flowers is somewhere between 200 and 500. How many flowers are in the garden?Amazingly enough, the problem actually has a unique solution! Doesn’t this surprise you?&lt;/blockquote&gt;&lt;p&gt;Have fun!&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-2487354129772750654?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/06/what-does-do-when-used-as-unary.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>22</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-4217991168585523478</guid><pubDate>Wed, 25 Jun 2008 02:05:00 +0000</pubDate><atom:updated>2008-06-24T22:08:42.776-04:00</atom:updated><title>A bit of history and an interesting conjecture</title><description>&lt;blockquote&gt;We Smalltalkers used to think the advantages of our language were so significant that it would take over the world. We had a huge productivity advantage over C coders. Then C++ came along and gave C coders just enough to let them improve their productivity and their ability to write larger more complex systems. It still wasn&amp;#8217;t as good as Smalltalk, but it was better than C, and much more accessible to most programmers than Smalltalk.&lt;br /&gt;&lt;br /&gt;C++ eventually sucked up all the oxygen and Smalltalk is now only a language for hobbyists and the occasional programming god. I think this is the most likely threat to the Rails surplus, that C# or Scala or something can do a good enough job that people can double their productivity with far less of a change in mindset or tools, and eventually no one will care about the ten times (or whatever) productivity of Rails.&lt;br /&gt;&lt;br /&gt;&amp;#8220;Good enough is good enough.&amp;#8221;&lt;/blockquote&gt;&lt;div&gt;&amp;mdash;&lt;a href="http://blog.hasmanythrough.com/2008/5/31/quick-railsconf-update"&gt;Josh Susser&lt;/a&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-4217991168585523478?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/06/bit-of-history-and-interesting.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>3</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-861417926615539281</guid><pubDate>Tue, 24 Jun 2008 14:45:00 +0000</pubDate><atom:updated>2008-06-24T17:08:10.250-04:00</atom:updated><title>Interview questions I have never been asked, Episode I</title><description>Compare and contrast:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;some_array.any? { |n| n &gt; 100 }&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;And:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;!!some_array.detect { |n| n &gt; 100 }&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Which do you think is easier to read?&lt;br /&gt;&lt;br /&gt;Are classes and modules easier to read and understand when they have lots and lots of specific methods like &lt;a href="http://globalnerdy.com/2008/06/24/enumerating-enumerable-enumerableany/"&gt;#any?&lt;/a&gt; or are they easier to read and understand with a small number of axiomatic methods that can be composed and combined like #fold and #unfold? When you design a module or class, do you write lots of convenience methods in advance? Or do you refactor code by writing convenience methods when you find yourself repeating the same code? &lt;br /&gt;&lt;div class="book"&gt;&lt;hr/&gt;&lt;em&gt;&lt;a name="evtst|a|0672328844" href="http://www.amazon.com/gp/product/0672328844?ie=UTF8&amp;amp;tag=raganwald001-20&amp;amp;link_code=as3&amp;amp;camp=211189&amp;amp;creative=373489&amp;amp;creativeASIN=0672328844"&gt;&lt;img src="http://weblog.raganwald.com/uploaded_images/the_ruby_way.jpg" border="0"&gt;&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=raganwald001-20&amp;amp;l=as2&amp;amp;o=1&amp;amp;a=0672328844" alt="" style="border: medium none  ! important; margin: 0px ! important;" border="0" height="1" width="1"&gt;&lt;br&gt;&lt;br&gt;&lt;a name="evtst|a|0672328844" href="http://www.amazon.com/gp/product/0672328844?ie=UTF8&amp;amp;tag=raganwald001-20&amp;amp;link_code=as3&amp;amp;camp=211189&amp;amp;creative=373489&amp;amp;creativeASIN=0672328844"&gt;The Ruby Way&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=raganwald001-20&amp;amp;l=as2&amp;amp;o=1&amp;amp;a=0672328844" alt="" style="border: medium none  ! important; margin: 0px ! important;" border="0" height="1" width="1"&gt; is the perfect second Ruby book for serious programmers. The Ruby Way contains more than four hundred examples explaining how to do everything from distribute Ruby with Rinda to functional programming techniques.&lt;/em&gt;&lt;hr/&gt;&lt;/div&gt;&lt;br /&gt;If you do refactor code to eliminate duplication, is there an amount of duplication that is too small to matter, like "!!"? Or is there an underlying principle of documenting intent that you wish to make explicit?&lt;br /&gt;&lt;br /&gt;Is:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;do_something() if some_array.detect { |n| n &gt; 100 }&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Misleading because it doesn&amp;rsquo;t actually &lt;em&gt;use&lt;/em&gt; the element it detects? Or is it a reasonable idiom to test for an element&amp;rsquo;s existence without using a specific method like #any or #nil?&lt;br /&gt;&lt;br /&gt;Are applications easier to read and understand when they make use of lots and lots of specific methods like #any or are they easier to read and understand when they compose and combine a smaller number of axiomatic methods so that you aren&amp;rsquo;t constantly looking things up?&lt;br /&gt;&lt;br /&gt;Do you think applications should have large or small vocabularies?&lt;br /&gt;&lt;br /&gt;&lt;em&gt;This example can be easily translated to the language du jour, the underlying principle applies to programming in general&lt;/em&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-861417926615539281?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/06/interview-questions-i-have-never-been.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>14</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-8802494876056821164</guid><pubDate>Mon, 23 Jun 2008 01:25:00 +0000</pubDate><atom:updated>2008-06-23T22:15:40.932-04:00</atom:updated><title>Macros, Hygiene, and Call By Name in Ruby</title><description>&lt;blockquote&gt;Never send a macro to do a function&amp;#8217;s job.&lt;/blockquote&gt;&lt;br /&gt;Sound advice, however just because functions (or methods) are better than macros for the things they both can do, that doesn&amp;#8217;t mean functions can do everything macros can do. Let&amp;#8217;s look at &lt;a href="http://andand.rubyforge.org/" title="Object#andand"&gt;andand&lt;/a&gt; for a moment. When you write:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;foo().andand.bar(blitz())&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Using the andand gem, Ruby treats this something like:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;temp1 = foo()&lt;br /&gt;temp2 = temp1.andand&lt;br /&gt;temp3 = blitz()&lt;br /&gt;temp2.bar(temp3)&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;As it happens, if you call nil.andand.bar(blitz()), it will return nil. But it will still evaluate blitz() before returning nil. What &lt;em&gt;I&lt;/em&gt; would expect from something named andand is that if foo() is nil, Ruby will never evaluate blitz(). Something like:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;temp1 = foo()&lt;br /&gt;if temp1.nil?&lt;br /&gt;    nil&lt;br /&gt;else&lt;br /&gt;    temp2 = blitz()&lt;br /&gt;    temp1.bar(temp2)&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;What we want is that when we pass blitz() to andand, it is not evaluated &lt;em&gt;unless the andand function uses it&lt;/em&gt;. The trouble is, you cannot write an andand method in Ruby that delivers these semantics.&lt;br /&gt;&lt;br /&gt;Let&amp;#8217;s hand wave over the difference between methods and functions for a moment and just look at calling functions. We&amp;#8217;ll consider writing &amp;#8220;our_and,&amp;#8221; a function that emulates the short-circuit evaluation behaviour of Ruby&amp;#8217;s &amp;#8220;&amp;amp;&amp;amp;&amp;#8221; and &amp;#8220;and&amp;#8221; operators. Ruby (and most other languages in use these days) uses &lt;a href="http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_value" title="Evaluation strategy - Wikipedia, the free encyclopedia"&gt;call-by-value&lt;/a&gt; when it passes parameters to functions. In other words, when you write:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;our_and(foo(), blitz())&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Ruby turns that into something that looks like this:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;var temp1 = foo()&lt;br /&gt;var temp2 = blitz()&lt;br /&gt;our_and(temp1, temp2)&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;It doesn&amp;#8217;t matter if the function our_and uses blitz() internally or not, it is evaluated &lt;em&gt;before&lt;/em&gt; our_and is called and its value is passed to our_and. Whereas our &amp;#8220;if&amp;#8221; statement in the previous example does not evaluate &amp;#8220;blitz()&amp;#8221; unless &amp;#8220;foo().andand&amp;#8221; is not nil.&lt;br /&gt;&lt;br /&gt;Well, well, well. The inescapable conclusion is that there are some sequences of expressions in Ruby that cannot be represented as functions or methods. That&amp;#8217;s right, &lt;em&gt;functions and methods can&amp;#8217;t do everything that Ruby code can do&lt;/em&gt;.&lt;br /&gt;&lt;br /&gt;Macros and code rewriting can do an awful lot. The implementation of andand in the &lt;a href="http://rewrite.rubyforge.org/" title="rewrite"&gt;rewrite&lt;/a&gt; gem &lt;em&gt;does&lt;/em&gt; rewrite code. When you write:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;with(andand) do&lt;br /&gt;    # ...&lt;br /&gt;    foo().andand.bar(blitz())&lt;br /&gt;    # ...&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Rewrite rewrites your code in place to look something like:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;# ...&lt;br /&gt;lambda do |__121414053598468__|&lt;br /&gt;    if __121414053598468__.nil?&lt;br /&gt;        nil&lt;br /&gt;    else&lt;br /&gt;        __121414053598468__.bar(blitz())&lt;br /&gt;    end&lt;br /&gt;end.call(foo)&lt;br /&gt;#...&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;And for that reason when you write foo().andand.bar(blitz()) using the rewrite gem instead of the andand gem, blitz() is not evaluated if foo() is nil. Big difference!! So it looks like one way to get around call-by-value is to rewrite your Ruby code. Excellent. Or is it?&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;What&amp;#8217;s wrong with rewrite&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Right now, the rewrite gem supports writing sexp processors. These are objects that encapsulate a way of transforming sexps. For example, here is the code that transforms expressions like &amp;#8220;foo().andand.bar(blitz()):&amp;#8221;&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;  def process_call(exp)&lt;br /&gt;    exp.shift&lt;br /&gt;    receiver_sexp = exp.first&lt;br /&gt;    if matches_andand_invocation(receiver_sexp)&lt;br /&gt;      exp.shift&lt;br /&gt;      mono_parameter = Rewrite.gensym()&lt;br /&gt;      s(:call, &lt;br /&gt;        s(:iter, &lt;br /&gt;          s(:fcall, :lambda), &lt;br /&gt;          s(:dasgn_curr, mono_parameter), &lt;br /&gt;          s(:if, &lt;br /&gt;            s(:call, s(:dvar, mono_parameter), :nil?), &lt;br /&gt;            s(:nil), &lt;br /&gt;            begin&lt;br /&gt;              s(:call, &lt;br /&gt;                s(:dvar, mono_parameter), &lt;br /&gt;                *(exp.map { |inner| process_inner_expr inner })&lt;br /&gt;              )&lt;br /&gt;            ensure&lt;br /&gt;              exp.clear&lt;br /&gt;            end&lt;br /&gt;          )&lt;br /&gt;        ), &lt;br /&gt;        :call, &lt;br /&gt;        s(:array, &lt;br /&gt;          process_inner_expr(receiver_sexp[1])&lt;br /&gt;        )&lt;br /&gt;      )&lt;br /&gt;    else&lt;br /&gt;      begin&lt;br /&gt;        s(:call,&lt;br /&gt;          *(exp.map { |inner| process_inner_expr inner })&lt;br /&gt;        )&lt;br /&gt;      ensure&lt;br /&gt;        exp.clear&lt;br /&gt;      end&lt;br /&gt;    end&lt;br /&gt;  end&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;And that&amp;#8217;s just a third of andand: There is another method that handles expressions like &amp;#8220;foo().andand { |x| x.bar(blitz()) }&amp;#8221; and a third that handles &amp;#8220;foo().andand(&amp;amp;bar_proc).&amp;#8221; Brutal.&lt;br /&gt;&lt;br /&gt;Now, rewriting code has many other uses. One on my wish list is a rewriter that transforms expressions like: &amp;#8220;foo.select { |x| &amp;#8230; }.map { |y| &amp;#8230; }.inject { |z| &amp;#8230; }&amp;#8221; into one big inject as an optimization. So I&amp;#8217;m not ready to throw rewrite in the trash can just yet. But there&amp;#8217;s no way I want to be writing all that out by hand every time I want to implement a function but work around call-by-value semantics.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;What about macros?&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Why can&amp;#8217;t I write:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;def_macro our_and(x,y)&lt;br /&gt;    ((temp = x) ? (y) : (temp))&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&amp;#8230;And have it automatically expand my code such that when I write:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;# ...&lt;br /&gt;foo = our_and(bar(), blitz())&lt;br /&gt;# ...&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;The macro expander rewrites it as:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;# ...&lt;br /&gt;foo = ((temp = bar() ? blitz() : temp)&lt;br /&gt;# ...&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Wouldn&amp;#8217;t that work? Maybe. Then again, maybe not.&lt;br /&gt;&lt;br /&gt;The problem given above&amp;#8212;working around call-by-value&amp;#8212;is just one small problem. A macro implementation would solve that problem, but there&amp;#8217;s an awful lot of overhead required to make the implementation work, and whatever you do ends up being an incredibly leaky abstraction.&lt;br /&gt;&lt;br /&gt;Take our example above. What happens if we have our own variable named temp? Does it get clobbered by expanding our_and? Or do we rename temp? Or do some automagic jigger-pokery with scopes?&lt;br /&gt;&lt;br /&gt;Getting macros right is very tricky. I don&amp;#8217;t personally plan to try my hand at implementing macros until I&amp;#8217;m an expert on the subject of &lt;a href="http://www.bookshelf.jp/texi/onlisp/onlisp_10.html" title="Onlisp:  Variable Capture"&gt;variable capture&lt;/a&gt; and can hold forth on the design trade-offs inherent in different schemes for implementing &lt;a href="http://en.wikipedia.org/wiki/Hygienic_macro" title="Hygienic macro - Wikipedia, the free encyclopedia"&gt;hygienic macros&lt;/a&gt;. But that&amp;#8217;s just me.&lt;br /&gt;&lt;br /&gt;Perhaps there are other ways to solve it without diving into a full-blown macro facility?&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Lambdas and blocks&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Indeed there are other ways. Ruby already has one-and-a-half of them: blocks and lambdas. Using blocks and lambdas, you can control evaluation precisely. The andand gem actually does support short-circuit semantics using a block. When you write:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;nil.andand { |x| x.foo(blitz()) }&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;It does &lt;em&gt;not&lt;/em&gt; evaluate blitz(). This alternate way of using andand supports the semantics we want by explicitly placing the code that should not be eagerly evaluated in a block. Given patience and a taste for squiggly braces, you can create non-standard evaluation without resorting to macros.&lt;br /&gt;&lt;br /&gt;We said at the beginning that the reason we cannot use functions and methods to represent everything we can write in code is because Ruby uses call-by-value to pass parameters to functions. One way to work around that is this: instead of passing the value of each expression to a function, we can pass the expression itself, wrapped up in its own lambda.&lt;br /&gt;&lt;br /&gt;Then, when the function needs the value, it can call the lambda. This technique has a name: it is called &lt;a href="http://en.wikipedia.org/wiki/Thunk#Thunk_as_delayed_computation" title="Thunk as delayed computation"&gt;thunking&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;We could implement our_and as follows:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;our_and = lambda { |x,y|&lt;br /&gt;    if temp = x.call&lt;br /&gt;        y.call&lt;br /&gt;    else&lt;br /&gt;        temp&lt;br /&gt;    end&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Then when we call it, we could wrap our parameters in lambdas:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;our_and.call(&lt;br /&gt;    lambda { a() },&lt;br /&gt;    lambda { b() }&lt;br /&gt;)&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Verify for yourself that this produces the behaviour we want, without the worry of our local variables messing things up for the calling code. Let&amp;#8217;s go further: we can implement functions with a variable number of arguments using an enumeration of thunks. For example, we could write:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;def try_these(*clauses)&lt;br /&gt;    clauses.each { |clause| return clause.call rescue nil }&lt;br /&gt;    nil&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;And call our function like this:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;try_these(&lt;br /&gt;    lambda { http_util.fetch(url, :login_as =&amp;gt; :anonymous) },&lt;br /&gt;    lambda { http_util.fetch(url, :login_as =&amp;gt; ['user', 'password']) },&lt;br /&gt;    lambda { default_value() }&lt;br /&gt;)&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;We have just implemented the &lt;a href="http://www.prototypejs.org/api/utility/try-these" title="Prototype JavaScript framework:  Utility Methods.Try.these"&gt;Try.these&lt;/a&gt; function from the Prototype Javascript library.&lt;br /&gt;&lt;br /&gt;This technique gets us almost all of what we want for this common case of wanting to work around call-by-value semantics. As you can surmise from the fact that it has a name, it is not some newfangled shiny toy idea, it goes back to ALGOL 60, where it was known as &lt;a href="http://foldoc.org/?call-by-name" title="call-by-name from FOLDOC"&gt;call-by-name&lt;/a&gt;. (PHP has something called &amp;#8220;Call By Name,&amp;#8221; but it has a lot more in common with C++ references than it does with ALGOL parameter passing.)&lt;br /&gt;&lt;br /&gt;The application of call-by-name as a substitute for full-blown macros isn&amp;#8217;t novel either. Joel Klein pointed out that &lt;a href="http://jfkbits.blogspot.com/2008/05/call-by-need-lambda-poor-mans-macro.html" title="Call by Need Lambda a Poor Man's Macro?"&gt;Call by need is a poor man&amp;#8217;s macro&lt;/a&gt;. Another suggestion along similar lines is to &lt;a href="http://arclanguage.org/item?id=7216" title="Arc Forum | Rethinking macros"&gt;rethink macros in Arc&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;thunks: ugly name, ugly code&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Our thunking approach solves a lot of our problems, but the implementation severely protrudes into the interface! We could argue that since our call-by-name functions have different behaviour than ordinary functions or methods, they ought to have different syntax.&lt;br /&gt;&lt;br /&gt;That&amp;#8217;s a reasonable point of view, and that&amp;#8217;s exactly how languages like Smalltalk work: everything that involves delaying evaluation in some way uses blocks, even the if statements, which are methods that take blocks as arguments. So in Smalltalk, everything is consistent.&lt;br /&gt;&lt;br /&gt;Ruby, OTOH, is not consistent. Operators like &amp;#8220;&amp;amp;&amp;#8221; and &amp;#8220;|&amp;#8221; are actually methods with call-by-value semantics, while operators like &amp;#8220;&amp;amp;&amp;amp;&amp;#8221; and &amp;#8220;||&amp;#8221; are special forms with call-by-value semantics. Likewise if you only need to delay one expression you can use a block, but if you need to delay two or more, you need at least one lambda. So another reasonable point of view is that we should follow Ruby&amp;#8217;s philosophy of making the common case easy to use and not become reductionists trying to build everything out of five axiomatic forms.&lt;br /&gt;&lt;br /&gt;So we have one approach&amp;#8212;rewriting&amp;#8212;that is crazy-hard to write but produces nicely readable code. And we have another approach&amp;#8212;thunking&amp;#8212;that is easy to write but produces unsightly boilerplate.&lt;br /&gt;&lt;br /&gt;Maybe what we want is a rewriter, but we want an easier way to write rewriters for this simple case?&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Called by name&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Here&amp;#8217;s how we could define and use a call-by-name function called &amp;#8220;our_and&amp;#8221;:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;with (&lt;br /&gt;    called_by_name(:our_and) { |x,y|&lt;br /&gt;        if temp = x&lt;br /&gt;            y&lt;br /&gt;        else&lt;br /&gt;            temp&lt;br /&gt;        end&lt;br /&gt;    }&lt;br /&gt;) do&lt;br /&gt;    # ...&lt;br /&gt;    foo = our_and(bar(), blitz()) # method-like syntactic sugar&lt;br /&gt;    # ...&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;What we just did is manufacture a rewriter without any sexps. Instead of getting rid of sexps, we&amp;#8217;re treating them like assembler and using a declarative language to write the assembler for us. Our rewriter dutifully rewrites our code to look something like:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;our_and = lambda { |x,y|&lt;br /&gt;    if temp = x.call&lt;br /&gt;        y.call&lt;br /&gt;    else&lt;br /&gt;        temp&lt;br /&gt;    end&lt;br /&gt;end&lt;br /&gt;# ...&lt;br /&gt;foo = our_and.call(&lt;br /&gt;    lambda { bar() },&lt;br /&gt;    lambda { blitz() }&lt;br /&gt;)&lt;br /&gt;# ...&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;We can define a rewriter for functions with splatted parameters too:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;with(&lt;br /&gt;    called_by_name(:try_these) { |*clauses|&lt;br /&gt;        clauses.each { |clause| return clause rescue nil }&lt;br /&gt;        nil&lt;br /&gt;    }&lt;br /&gt;) do&lt;br /&gt;    # ...&lt;br /&gt;    try_these(&lt;br /&gt;        http_util.fetch(url, :login_as =&amp;gt; :anonymous),&lt;br /&gt;        http_util.fetch(url, :login_as =&amp;gt; ['user', 'password']),&lt;br /&gt;        default_value()&lt;br /&gt;    )&lt;br /&gt;    # ...&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Becomes something like:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;try_these = lambda { |*clauses|&lt;br /&gt;    clauses.each { |clause| return clause.call rescue nil }&lt;br /&gt;    nil&lt;br /&gt;}&lt;br /&gt;# ...&lt;br /&gt;try_these.call(&lt;br /&gt;    lambda { http_util.fetch(url, :login_as =&amp;gt; :anonymous) },&lt;br /&gt;    lambda { http_util.fetch(url, :login_as =&amp;gt; ['user', 'password']) },&lt;br /&gt;    lambda { default_value() }&lt;br /&gt;)&lt;br /&gt;# ...&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;blockquote&gt;It goes, boys!&lt;/blockquote&gt;&lt;div&gt;&amp;#8212;Lynn Hill after becoming the first person of either sex to climb The Nose of El Capitan, all free.&lt;/div&gt;&lt;br /&gt;As of now, the &lt;a href="http://rewrite.rubyforge.org"&gt;rewrite&lt;/a&gt; gem supports called_by_name. You can write your own functions with call-by-name semantics using called_by_name just as you see here. As is standard with the rewrite gem, only the code in the do&amp;#8230; end block is affected by your change.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;call-by-name, in summary&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;To summarize, with the rewrite gem you can write functions that have call-by-name semantics without wrestling sexps into submission or encumbering your code with a lot of superfluous lambdas and calls:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;with(&lt;br /&gt;    called_by_name(:try_these) { |*clauses|&lt;br /&gt;        clauses.each { |clause| return clause rescue nil }&lt;br /&gt;        nil&lt;br /&gt;    },&lt;br /&gt;    called_by_name(:our_and) { |x,y|&lt;br /&gt;        if temp = x&lt;br /&gt;            y&lt;br /&gt;        else&lt;br /&gt;            temp&lt;br /&gt;        end&lt;br /&gt;    }&lt;br /&gt;) do&lt;br /&gt;    # ...&lt;br /&gt;    try_these(&lt;br /&gt;        http_util.fetch(url, :login_as =&amp;gt; :anonymous),&lt;br /&gt;        http_util.fetch(url, :login_as =&amp;gt; ['user', 'password']),&lt;br /&gt;        default_value()&lt;br /&gt;    )&lt;br /&gt;    # ...&lt;br /&gt;    foo = our_and(bar(), blitz())&lt;br /&gt;    # ...&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;This is a win when you don&amp;rsquo;t want your code encumbered with more lambdas than business logic. It may be a matter of taste, but part of what I like about Ruby having a special case for blocks is that they act as a huge hint that an expression is temporary: a block after #map suggests we are only using that expression in one place. Whereas when I see &amp;ldquo;Proc.new&amp;rdquo; or &amp;ldquo;lambda,&amp;rdquo; I expect that the expression will be passed around and used elsewhere.&lt;br /&gt;&lt;br /&gt;Functions with call-by-name semantics communicate the same thing as blocks: the expressions are to be consumed by the function. When I see a lambda being passed to a function, I automatically expect it to be saved and possibly used elsewhere. For that reason, I prefer call-by-name semantics when an expression is not meant to be persisted beyond the function invocation.&lt;br /&gt;&lt;br /&gt;Now, called_by_name is not a replacement for macros. There are lots of things macros can do that called_by_name cannot do (not to mention that there are lots of things code rewriting can do that macros cannot do). But just as Ruby&amp;#8217;s blocks are a deliberate attempt to make a common case for anonymous functions easy to write, called_by_name makes a common case for macros easy to write and safe from variable capture problems.&lt;br /&gt;&lt;br /&gt;Of course, called_by_name does so with lots of anonymous functions, and that is a much more expensive implementation than using a hygienic macro to rewrite code inline. But it feels like a move in an interesting direction: if it is a win to sometimes meta-program Ruby&amp;#8217;s syntax with DSLs, it ought to also be a win to sometimes meta-program Ruby&amp;#8217;s semantics with call-by-name functions.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;afterword&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;So&amp;hellip; Is this merely a way to replicate things that are already built into Ruby but do them fifty times slower?&lt;br /&gt;&lt;br /&gt;I don&amp;rsquo;t know how to answer that question. When I heard Matz talk about Ruby at &lt;a href="http://weblog.raganwald.com/2007/01/where-were-you-on-saturday-november-9.html" title="Where were you on Saturday, November 9, 2002?"&gt;LL1&lt;/a&gt;, I didn&amp;rsquo;t catch the part of his speech where he described how to use metaprogramming to build a really neat web development framework. When you first see a new tool, you naturally start by applying it to problems you already know how to solve with your existing tools in the same way you have always solved such problems.&lt;br /&gt;&lt;br /&gt;Only later, after this tool becomes perfectly natural to you, do you start to think of entirely new ways to use the tool. I&amp;rsquo;m not there yet, but my experience tells me that it&amp;rsquo;s always a win to have more freedom, to have fewer things you can&amp;rsquo;s do with a language.&lt;br /&gt;&lt;br /&gt;If just one person&amp;mdash;maybe it&amp;rsquo;s me, maybe it&amp;rsquo;s somebody else&amp;mdash;leans forward one day and sees a new way of solving a problem with call-by-name semantics, I&amp;rsquo;ll consider working on this feature time well spent.&lt;br /&gt;&lt;br /&gt;It probably won&amp;rsquo;t be something trivial like replicating short-circuit boolean operators. But it will be interesting, and I&amp;rsquo;m looking forward to finding out what it is.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-8802494876056821164?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/06/macros-hygiene-and-call-by-name-in-ruby.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>7</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-6433618312064877824</guid><pubDate>Sun, 22 Jun 2008 11:42:00 +0000</pubDate><atom:updated>2008-06-27T22:13:12.953-04:00</atom:updated><title>A little something about dumbing code down to the lowest common denominator</title><description>&lt;blockquote&gt;When the productive have to ask permission from the unproductive in order to produce, then you may know your culture is doomed.&lt;/blockquote&gt;&lt;div&gt;&amp;mdash;Ayn Rand, via &lt;a href="http://matt.blogs.it/entries/00002867.html"&gt;Matt Mower&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;hr/&gt;&lt;br /&gt;&lt;em&gt;update:&lt;/em&gt; &lt;a href="http://chalain.livejournal.com/74633.html"&gt;Chalain nails it&lt;/a&gt;, especially when he writes &amp;ldquo;&amp;hellip; she's right about those two little words: ask permission. And not about dumbing down code.&amp;rdquo; Although the examples he gives are nothing like the examples that crossed my mind.&lt;br /&gt;&lt;br /&gt;I have been happiest when I have worked with people much, much smarter than I am, people who forced me to raise my game. I recall that when I worked on JProbe Threadalyzer, the three key people on my team were Steve Rosenberg, Christian Jaekl, and John MacMillan. Steve was my manager, and he forced me to raise my game as a team lead. Christian was our domain expert, he had written his Masters Thesis on analyzing the behaviour of concurrent software, and he forced me to immerse myself deeply in concurrency just to understand what he was designing. And John was a C++ Wizard. I recall him being extremely patient with me a I got up to speed writing production C++ code.&lt;br /&gt;&lt;br /&gt;All three were patient with my shortcomings, but our culture was to help me be more productive, to help me understand their ideas. Not to hold them back so that I could stay in my comfort zone.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-6433618312064877824?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/06/little-something-about-dumbing-code.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>13</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-6708145457801438905</guid><pubDate>Wed, 18 Jun 2008 03:30:00 +0000</pubDate><atom:updated>2008-06-22T22:10:11.492-04:00</atom:updated><title>Not going dark</title><description>Rubyforge is now hosting an &amp;ldquo;initial pre-release of a preview of an alpha of an undocumented proof-of-concept&amp;rdquo; of the &lt;a href="http://rewrite.rubyforge.org/"&gt;rewrite&lt;/a&gt; gem. More on this presently, but the important (and really the only thing of interest) about rewrite is that when you use rewrite to write:&lt;br /&gt;&lt;br /&gt;&lt;em&gt;Person.find_by_last_name("Braithwaite").andand.first_name&lt;/em&gt;&lt;br /&gt;&lt;br /&gt;...You are not opening the Object, Person or Nil classes to add an andand method, nor are you creating a weird temporary BlankSlate object. Rewrite does its thing by rewriting Ruby code: it performs &lt;em&gt;syntactic&lt;/em&gt; metaprogramming, much as Lisp macros rewrite Lisp code.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;what problem does rewrite solve?&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Recall that when you use the &amp;ldquo;standard&amp;rdquo; implementation of things like &lt;a href="http://andand.rubyforge.org"&gt;andand&lt;/a&gt; or &lt;a href="http://ozmm.org/posts/try.html"&gt;try&lt;/a&gt;, you are openly modifying core classes like Object.&lt;br /&gt;&lt;br /&gt;Therefore, you are reaching out and touching every line of code in your project. You probably aren&amp;rsquo;t breaking everything, but even if the chance of introducing a bug by adopting something like &amp;ldquo;try&amp;rdquo; is infinitesimal for each source code file in your project, the chance grows greater and greater as your application grows.&lt;br /&gt;&lt;br /&gt;The problem is that you are introducing a change on Object, and everything depends on Object. This is very different than introducing a change in your code. In that case, only the other bits of code that directly depend on your code are at risk.&lt;br /&gt;&lt;br /&gt;Also, imagine if you introduce try and are careful not to break anything. Now somebody else wakes up one day and decides they need a method that works like Prototype&amp;rsquo;s &lt;a href="http://www.prototypejs.org/api/utility/try-these"&gt;Try.these&lt;/a&gt;. They call it &amp;ldquo;try.&amp;rdquo; They just broke your code, dude! Not only are you making everything dependant upon your version of try, but your code is dependent upon everyone else not breaking try as well. It&amp;rsquo;s a train-wreck waiting to happen.&lt;br /&gt;&lt;br /&gt;Rewrite restricts things like andand or try to your code and your code alone. Sure, if you introduce a bug in your code, you may break things that directly depend on your code. But if you introduce &amp;ldquo;try&amp;rdquo; using rewrite instead of modifying Object, you will not reach out across your project and break something entirely unrelated that happens to have defined its own version of try in a completely different way.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;how does it work?&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Rewrite takes your code, converts it to an sexp with Parse Tree, then rewrites the sexp using one or more rewriters you specify. Finally, it converts the sexp back to Ruby with Ruby2Ruby and evals it. It does this when the code is first read, not every time it is invoked, so we mitigate the &amp;ldquo;do not use andand in a tight loop&amp;rdquo; problem.&lt;br /&gt;&lt;br /&gt;For example, rewrite converts this:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;emails.find_by_email(email).try(:destroy)&lt;/code&gt;&lt;/pre&gt;Into:&lt;pre&gt;&lt;code&gt;&lt;br /&gt;lambda { |receiver, method|&lt;br /&gt;   receiver.send(method) if receiver.respond_to? method&lt;br /&gt; }.call(emails.find_by_email(email), :destroy)&lt;/code&gt;&lt;/pre&gt;And this:&lt;pre&gt;&lt;code&gt;&lt;br /&gt; numbers.andand.inject(base_sum()) { |total, number| total + number }&lt;/code&gt;&lt;/pre&gt;Into:&lt;pre&gt;&lt;code&gt;&lt;br /&gt; lambda { |__1234567890__|&lt;br /&gt;   if __1234567890__.nil?&lt;br /&gt;     nil&lt;br /&gt;   else&lt;br /&gt;     __1234567890__.inject(base_sum()) { |total, number| total + number }&lt;br /&gt;   end&lt;br /&gt; }.call(numbers)&lt;/code&gt;&lt;/pre&gt;Note that with the examples, the names &amp;ldquo;andand&amp;rdquo; and &amp;ldquo;try&amp;rdquo; completely go away. If someone else defines a try method elsewhere, it will not affect your code because your code never executes a method called try.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;the most important open problem to solve in this area&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;At the moment that is a huge PITA when creating new rewriters. I don&amp;rsquo;t think that &lt;a href="http://ola-bini.blogspot.com/2008/06/applications-and-libraries.html" title="Applications and Libraries"&gt;it's OK that a language makes it harder for a library creator than for an application developer&lt;/a&gt;, so I am working on making it easy to write things like andand or try.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;puzzles for language weenies&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Note that the andand example above uses gemsym for its parameter while the try example does not. &lt;a title="Macros, Hygiene, and Call By Name in Ruby" href="http://weblog.raganwald.com/2008/06/macros-hygiene-and-call-by-name-in-ruby.html"&gt;Why&lt;/a&gt;? What could break if it used a name like &amp;ldquo;receiver?&amp;rdquo; If you can figure out the salient difference between these two example rewrites, you can probably explain why rewriting try produces exactly the same semantics as the original open classes implementation, but rewriting andand produces a subtle change in semantics.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-6708145457801438905?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/06/not-going-dark.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>19</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-8842105618136377860</guid><pubDate>Sat, 14 Jun 2008 11:15:00 +0000</pubDate><atom:updated>2008-06-14T08:34:19.547-04:00</atom:updated><title>Today's public key is { :n =&gt; 46, :e =&gt; 5 }</title><description>&lt;pre&gt;&lt;code&gt;&lt;br /&gt;def rsa_encrypt(message, public_key)&lt;br /&gt;  n = public_key[:n]&lt;br /&gt;  e = public_key[:e]&lt;br /&gt;  n_arr = message.downcase.scan(/[a-z]| /).map { |character|&lt;br /&gt;    "abcdefghijklmnopqrstuvwxyz ".index(character)&lt;br /&gt;  }&lt;br /&gt;  n_arr.map { |m|&lt;br /&gt;    (m ** e).modulo n&lt;br /&gt;  }&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def rsa_decrypt(ciphertext, private_key)&lt;br /&gt;  n = private_key[:n]&lt;br /&gt;  d = private_key[:d]&lt;br /&gt;  n_arr = ciphertext.map { |c| &lt;br /&gt;    (c ** d).modulo n&lt;br /&gt;  }&lt;br /&gt;  n_arr.map { |n| "abcdefghijklmnopqrstuvwxyz "[n,1] }.join('')&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;And the secret message is: [11, 38, 13, 0, 24, 36, 16, 26, 36, 18, 24, 36, 1, 16, 21, 11, 17, 13, 0, 24]&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-8842105618136377860?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/06/todays-public-key-is-modulus-46-e-5.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>9</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-8015758512711595388</guid><pubDate>Mon, 09 Jun 2008 11:06:00 +0000</pubDate><atom:updated>2008-06-09T08:16:50.418-04:00</atom:updated><title>Bitchiness also sucks</title><description>&lt;blockquote&gt;&amp;#8220;This framework I never use in a programming language I also never use is designed in a way that I don&amp;#8217;t like, so I&amp;#8217;m going to raise a ruckus even though I&amp;#8217;m never going to use it and there are other frameworks that meet my design standards better&amp;#8221; just seems like a dumb thing to write a bitchy blog post about.&lt;/blockquote&gt;&lt;div&gt;&amp;mdash;Chuck Hoffman, &lt;a href="http://nothinghappens.net/?p=324"&gt;activerecord sucks, but it doesn't matter&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Chuck, thank you for saying what needs to be said. Bitchy blog posts purport to describe shortcomings, but are they anything more than thinly veiled chest thumping from an author who feels he is the smartest person in the room?&lt;br /&gt;&lt;br /&gt;p.s. Question: Are bitchy blog posts about bitchy blog posts (like this one!) still bitchy blog posts?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-8015758512711595388?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/06/bitchiness-also-sucks.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>6</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-4848135369923511619</guid><pubDate>Thu, 05 Jun 2008 16:59:00 +0000</pubDate><atom:updated>2008-06-05T13:12:47.683-04:00</atom:updated><title>Skirting the edge of topicality: Five days left to register for RubyFringe</title><description>Pete Forde wrote to say that there are only 5 days left to &lt;a href="http://rubyfringe.eventbrite.com/"&gt;register&lt;/a&gt; for &lt;a href="http://rubyfringe.com/"&gt;RubyFringe&lt;/a&gt;, and currently fewer than 20 tickets left.&lt;br /&gt;&lt;br /&gt;Co&amp;iuml;ncidentally, I have submitted my title and abstract:&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Ruby.rewrite(Ruby)&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;An introduction to writing Ruby that reads, writes, and rewrites Ruby. In an extremely short period of time we will extend the Ruby language to include new conditional expressions, add new forms of evaluation such as call-by-name and call-by-need, and if time permits we&amp;#8217;ll define new recursive combinators.&lt;br /&gt;&lt;br /&gt;In other words we&amp;#8217;ll practice the truest form of constructive criticism: Instead of complaining about missing language features, we&amp;#8217;ll implement them.&lt;/em&gt;&lt;br /&gt;&lt;br /&gt;Luckily for you, the &lt;a href="http://rubyfringe.com/speakers"&gt;other speakers&lt;/a&gt; are people with actual talent and a knack for entertaining people. What are you waiting for? &lt;a href="http://rubyfringe.eventbrite.com/"&gt;Register!&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-4848135369923511619?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/06/skirting-edge-of-topicality-five-days.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-2031631425815760317</guid><pubDate>Fri, 30 May 2008 19:02:00 +0000</pubDate><atom:updated>2008-05-31T18:00:21.965-04:00</atom:updated><title>"Lets" organize our Ruby Code</title><description>This post is for folks interested in the &lt;a href="http://ick.rubyforge.org/" title="Invocation Construction Kit"&gt;Invocation Construction Kit&lt;/a&gt; for Ruby. There is a new invocation, Ick::Syntax::Lets:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;lets(&lt;br /&gt;    :person =&amp;gt; Person.find(:first, ...),&lt;br /&gt;    :place  =&amp;gt; City.select { ... },&lt;br /&gt;    :thing  =&amp;gt; %w(ever loving blue eyed)&lt;br /&gt;) {&lt;br /&gt;    "#{person.name} lives in #{place} where he is known as the '#{thing.join(' ')} thing.'"&lt;br /&gt;}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Quite simply, #lets provides you with a way of making block-local variables. Ick already includes #let, which does almost exactly the same thing. However, #let is limited to just one variable:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;let(Person.find(:first, ...)) { |person| ... }&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Expanding #let to multiple variables with its existing syntax just doesn&amp;#8217;t scale properly:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;let(&lt;br /&gt;    Person.find(:first, ...),&lt;br /&gt;    City.select { ... },&lt;br /&gt;    %w(ever loving blue eyed)&lt;br /&gt;) { |person, place, thing|&lt;br /&gt;    "#{person.name} lives in #{place} where he is known as the '#{thing.join(' ')} thing.'"&lt;br /&gt;}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;Thus, the #lets syntax uses a hash so that the variable names are close to the expressions denoting their values.&lt;br /&gt;&lt;br /&gt;That&amp;#8217;s all. If you are interested in why anyone would need #lets, read on&amp;#8230;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Scope Creep&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Recently there has been a lot of interest in exploring the extremes of OO style. One of the tenets of such a style is to work with &lt;a href="http://binstock.blogspot.com/2008/04/perfecting-oos-small-classes-and-short.html" title="Perfecting OO's Small Classes and Short Methods"&gt;small classes and short methods&lt;/a&gt;. Why do you suppose we want to do that?&lt;br /&gt;&lt;br /&gt;Well, the underlying principle is to chunk things into small, workable pieces with clear purposes. This principle abounds everywhere: posts just like this are broken up into sections with headings and the prose is subdivided into paragraphs. So I quite agree with the principle behind small classes and short methods.&lt;br /&gt;&lt;br /&gt;__________. You just knew that a word like &amp;#8220;However&amp;#8221; would follow a paragraph like that, didn&amp;#8217;t you?&lt;br /&gt;&lt;br /&gt;The principle of subdivision is terrific. But are classes and methods the only mechanisms we have for subdividing code? In some languages, that may be true. In other languages, that is not true.&lt;br /&gt;&lt;br /&gt;For example, since version 1.1 Java has permitted classes to be nested inside of other classes, calling them &amp;#8220;inner classes.&amp;#8221; This is a very powerful technique of organizing code: If class A is the only class that ever uses class B, why should class B live in its own file, visible to every other class? Placing class B inside of class A is a big win: it is immediately clear that A is the only user of B, and when looking at the code in your IDE you do not see class B promoted to equal standing with A: it is clearly subordinate to A.&lt;br /&gt;&lt;br /&gt;Of course, placing class B inside of class A makes A a bigger class. Is that wrong? Perhaps it is at some times, but it&amp;#8217;s a big win at others. Remember we said B is subordinate to A? An inner class can be made private, explicitly telling the compiler and other programmers that it is limited in scope.&lt;br /&gt;&lt;br /&gt;Limiting scope is a very powerful organizing technique in code. We can debate how important it is that the compiler enforce scope, however given the importance of writing code for humans to read and understand, I&amp;#8217;m personally in favour of any technique that sends a strong &lt;a href="http://weblog.raganwald.com/2007/11/programming-conventions-as-signals.html" title="Programming conventions as signals"&gt;signal&lt;/a&gt; to your fellow programmers explaining the intended structure and organization of the code.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Small Methods&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;There are techniques for organizing methods into classes or modules, and techniques for organizing classes and modules into larger classes and modules. But what about individual lines of code? Are methods really the only mechanism we have for organization at the lowest level?&lt;br /&gt;&lt;br /&gt;I think not. Even within methods, there are certain practices that logically chunk your code into small, workable pieces with clear purposes. For example, Algol, Pascal, Modula, and many other languages support nested functions or procedures:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;procedure print(var j: integer);&lt;br /&gt;&lt;br /&gt;  function next(k: integer): integer;&lt;br /&gt;  begin&lt;br /&gt;    next := k + 1&lt;br /&gt;  end;&lt;br /&gt;&lt;br /&gt;begin&lt;br /&gt;  writeln('The total is: ', j);&lt;br /&gt;  j := next(j)&lt;br /&gt;end;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;It is clear that #next is used solely by #print. Since most OO languages do not permit nested procedures, the programmer is left to choose between making #nest a private method or carving #print out and making it a strategy class. Making #next a private method does keep it from prying eyes outside of the class, however it implies that all methods of the class may want to use it, which is clearly not the case.&lt;br /&gt;&lt;br /&gt;If we are allowed to nest objects, we can fake nested procedures with objects. Ruby&amp;#8217;s Proc class makes it easy:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;def print(j)&lt;br /&gt;    next = proc { |k|&lt;br /&gt;        k + 1&lt;br /&gt;    }&lt;br /&gt;    p "the total is: #{j}"&lt;br /&gt;    j = next.call(j)&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;(There is a fairly major difference in what these two snippets of code do thanks to the difference between call-by-value and call-by-reference, but let&amp;#8217;s wave our hands furiously and stick to the point about nesting functions.)&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Containing Variables&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;In imperative languages, one of our biggest headaches is managing &lt;a href="http://weblog.raganwald.com/2006/10/why-are-local-variables-bad.html" title="Why are local variables bad?"&gt;mutable local variables&lt;/a&gt;. If you only need one in one particular place, it is helpful to have a way of nesting the variable definition. In Java:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;for(int i=1; i&amp;lt;11; i++) {&lt;br /&gt;    StringBuffer j = new StringBuffer();&lt;br /&gt;    // ...&lt;br /&gt;}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;And in Perl (thanks Chromatic):&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;{&lt;br /&gt;  my $person = Person-&gt;find( first =&gt; ... );&lt;br /&gt;  my $place = City-&gt;select( sub { ... } );&lt;br /&gt;  my $thing = [qw( ever loving blue eyed )];&lt;br /&gt;&lt;br /&gt;  return $person-&gt;name() . " lives in $place where he is known as the "&lt;br /&gt;    . join( ' ', @$thing ) . ' thing.';&lt;br /&gt;}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;The variables i and j are limited in scope to the body of the for loop. This called block scoping, and I personally love it. Block scoping permits us to make small, self-contained blocks of code and use them inline. If we need to move them or change them, we know which things are limited in scope to the block and which reach outside of the block and thus might be affected by our changes.&lt;br /&gt;&lt;br /&gt;In Javascript we can &lt;a href="http://weblog.raganwald.com/2007/08/block-structured-javascript.html" title="Block-Structured Javascript"&gt;fake block scoping using procedures&lt;/a&gt;, but it&amp;#8217;s syntactically noisy. Can we do the same thing in Ruby? Yes, and that&amp;#8217;s exactly what #lets does:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;lets(&lt;br /&gt;    :person =&amp;gt; Person.find(:first, ...),&lt;br /&gt;    :place  =&amp;gt; City.select { ... },&lt;br /&gt;    :thing  =&amp;gt; %w(ever loving blue eyed)&lt;br /&gt;) {&lt;br /&gt;    "#{person.name} lives in #{place} where he is known as the '#{thing.join(' ')} thing.'"&lt;br /&gt;}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;This is a block with three block-local variables in it, just like you might find in Java. It breaks a complicated expression up into smaller pieces (&amp;#8220;How to find the person,&amp;#8221; &amp;#8220;How to find the place,&amp;#8221; &amp;#8220;What kind of thing we have,&amp;#8221; and finally &amp;#8220;How to describe it all as a string&amp;#8221;). And those pieces are all grouped together so you know they are not used elsewhere.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;A Hack, wrapped in a Workaround, inside a Kludge&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Unlike the other elements of Ick, #lets actually &lt;em&gt;rewrites your ruby code&lt;/em&gt;. The code example above is actually rewritten as:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;proc { |__121217088531733__|&lt;br /&gt;  lambda do |person, place, thing|&lt;br /&gt;    "#{person.name} lives in #{place} where he is known as the '#{thing.join(" ")} thing.'"&lt;br /&gt;  end.call(&lt;br /&gt;    __121217088531733__[:person], &lt;br /&gt;    __121217088531733__[:place], &lt;br /&gt;    __121217088531733__[:thing]&lt;br /&gt;  )&lt;br /&gt;}.call(&lt;br /&gt;    :person =&amp;gt; Person.find(:first, ...),&lt;br /&gt;    :place  =&amp;gt; City.select { ... },&lt;br /&gt;    :thing  =&amp;gt; %w(ever loving blue eyed)&lt;br /&gt;)&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;The rewritten code is then evaluated. At the moment, this happens every time you call #lets, so it is expensive. Even by Ruby standards. Hopefully, there will be a future version of Ick::Syntax that only rewrites by need or perhaps just once when the code is first read.&lt;br /&gt;&lt;br /&gt;So, #lets takes the syntactic noise of using procs to create block structure and hides it from us. How?&lt;br /&gt;&lt;br /&gt;Well, my first cut at it used &lt;a href="http://rubyforge.org/frs/shownotes.php?group_id=1513&amp;amp;release_id=17347"&gt;Ruby2Ruby&lt;/a&gt; and regular expressions. Then I was inspired by Aanand Prasad&amp;#8217;s &lt;a href="http://github.com/aanand/ruby-do-notation/tree/master"&gt;Haskell-style monad do-notation for Ruby&lt;/a&gt; to work directly with s-expressions. Although the code is technically longer, it&amp;#8217;s actually much, much better. For meta-syntactic programming, you need to work with the abstract syntax tree.&lt;br /&gt;&lt;br /&gt;And with &lt;a href="http://rubyforge.org/projects/parsetree/" title="RubyForge: ParseTree - ruby parse tree tools: Project Info"&gt;ParseTree&lt;/a&gt; and Ruby2Ruby, you have all the tools you need to write code that writes code, with the teeny-weeny proviso that what you want to do is translate your Ruby into Lisp, manipulate the Lisp, and then translate it back into Ruby:&lt;br /&gt;&lt;pre&gt;&lt;code&gt;&lt;br /&gt;def rewrite_sexp(names_to_values, sexp)&lt;br /&gt;  mono_parameter = :"__#{Time.now.to_i}#{rand(100000)}__"&lt;br /&gt;  # the next four assignments are exactly why we want #lets:&lt;br /&gt;  sorted_symbols = (names_to_values || {}).keys.map(&amp;:to_s).sort.map(&amp;:to_sym)&lt;br /&gt;  parameters = if sorted_symbols.size == 1&lt;br /&gt;    s(:dasgn_curr, sorted_symbols.first)&lt;br /&gt;  else&lt;br /&gt;    s(:masgn, s(:array, *sorted_symbols.map { |sym| s(:dasgn_curr, sym) }) )&lt;br /&gt;  end&lt;br /&gt;  values = s(:array,&lt;br /&gt;    *sorted_symbols.map { |sym|&lt;br /&gt;      s(:call, s(:dvar, mono_parameter), :[], s(:array, s(:lit, sym)))&lt;br /&gt;    }&lt;br /&gt;  )&lt;br /&gt;  body = sexp.last&lt;br /&gt;&lt;br /&gt;  s(:defn, :__anonymous__, &lt;br /&gt;    s(:bmethod, &lt;br /&gt;      s(:dasgn_curr, mono_parameter), &lt;br /&gt;      s(:call, &lt;br /&gt;        s(:iter, &lt;br /&gt;          s(:fcall, :lambda), &lt;br /&gt;          parameters,&lt;br /&gt;          body&lt;br /&gt;        ), &lt;br /&gt;        :call, &lt;br /&gt;        values&lt;br /&gt;      )&lt;br /&gt;    )&lt;br /&gt;  )&lt;br /&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;&lt;strong&gt;You know what to do:&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;sudo gem install &lt;a href="http://ick.rubyforge.org"&gt;ick&lt;/a&gt;&lt;/em&gt;&lt;br /&gt;&lt;br /&gt;Cheers, and thanks very much to &lt;a href="http://rubyforge.org/users/zenspider/"&gt;Ryan Davis&lt;/a&gt;, &lt;a href="http://rubyforge.org/users/drbrain/"&gt;Eric Hodel&lt;/a&gt;, &lt;a href="http://matt.blogs.it/" title="Curiouser and Curiouser!"&gt;Matt Mower&lt;/a&gt;, and &lt;a href="http://www.aanandprasad.com/"&gt;Aanand Prasad&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-2031631425815760317?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/05/lets-organize-our-ruby-code.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>14</thr:total></item><item><guid isPermaLink='false'>tag:blogger.com,1999:blog-7618424.post-3797327616198460736</guid><pubDate>Thu, 29 May 2008 15:44:00 +0000</pubDate><atom:updated>2008-05-29T12:01:48.673-04:00</atom:updated><title>A Limitless Resource</title><description>&lt;blockquote&gt;Spam is the only truly limitless resource on the web and the ability to resist the endless waves of spam may well well be the single most important requirement of future distributed computing architectures&amp;hellip;&lt;br /&gt;&lt;br /&gt;Anybody who proposes a web architecture that doesn&amp;rsquo;t provide a means to handle spam is just engaging in wishful thinking.&lt;/blockquote&gt;&lt;div&gt;&amp;mdash;&lt;a href="http://blogs.concedere.net:8080/blog/discipline/web/?permalink=Those-Who-Live-by-the-Spam.html"&gt;Those Who Live by the Spam&amp;hellip;&lt;/a&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7618424-3797327616198460736?l=weblog.raganwald.com%2Fwelcome.html' alt='' /&gt;&lt;/div&gt;</description><link>http://weblog.raganwald.com/2008/05/limitless-resource.html</link><author>noreply@blogger.com (Reginald Braithwaite)</author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>3</thr:total></item></channel></rss>