HOWTO: Win any contest by being the only one competing

Thu, Apr 6, 2006 2-minute read

As pointed out by Scott Hanselman, somehow – my get-answer script is being used as cudgel in a
Monad vs Ruby debate.  Ted Neward mentions how cool the script is (with a title bound to
stir Ruby natives.) Glenn Vanderburg, in kind, jumps to Ruby’s defense.

As far as the language goes, Glenn’s main point is that Ruby is much more concise than Monad.

This is where the title of my post comes from – it’s easy to win any contest if you’re the
only one competing in it :)  I write my aricles with a heavy prejudice towards teaching,
illustration, and explanation.  Without that style, the Monad script can be written in a form
that is nearly line-for-line equivalent to the Ruby example:

param([string] $question = $(throw "Please ask a question.")) 
[void] [Reflection.Assembly]::LoadWithPartialName("System.Web")
$webClient = new-object System.Net.WebClient

$text =  $webClient.DownloadString(
    "http://search.msn.com/encarta/results.aspx?q=$([Web.HttpUtility]::UrlEncode($question))")

if($text -match "<div id=`"results`">(.+?)</div></div><h2>Results</h2>") 
{ 
   $partialText = $matches[1]
   $partialText = $partialText -replace "<\s*a.*?>.+?</a>", ""
   $partialText = $partialText -replace "</(div|span)>", "`n" 
   $partialText = $partialText -replace "<[^>]*>", ""
   $partialText = ($partialText -replace "`n`n","`n").TrimEnd()
   $partialText
} 
else 
{ 
  "No answer found." 
}

In any case, computer languages are not a zero-sum game.  You don’t have to pick between Monad
and Ruby – I don’t.

[Edit: Bruce Payette offers this alternate “one-liner” :) ]

Just for grins, here’s the same thing as a 1-liner (i.e. 1 single expression.)

.{[Reflection.Assembly]::LoadWithPartialName("System.Web") -and "$args" -or $("Please ask a question.";return) -and (new-object Net.WebClient).DownloadString("http://search.msn.com/encarta/results.aspx?q=$([Web.HttpUtility]::UrlEncode(`"$args`"))") -match "<div id=`"results`">(.+?)</div></div><h2>Results</h2>" -and $(return ($matches[1] -replace "<\s*a.*?>.+?</a>", "" -replace "</(div|span)>", "`n"  -replace "<[^>]*>", "" -replace "`n`n","`n").TrimEnd()) -or $("No answer found.";return)}

Paste this into an Msh window followed by a question and you’ll get your answer. (We need to run an obfuscated msh contest sometime soon…)

In practice, this isn’t a great example for doing a language comparison - it’s more about libraries and regular expressions than it is about language features.

[Edit: Monad has now been renamed to Windows PowerShell. This script or discussion may require slight adjustments before it applies directly to newer builds.]