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

<channel>
	<title>Khaled alHabache's official blog &#187; khelll</title>
	<atom:link href="http://www.khelll.com/blog/author/admin/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.khelll.com/blog</link>
	<description>What web development means....</description>
	<lastBuildDate>Tue, 16 Mar 2010 23:21:41 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>StackOverflow cool Ruby questions 4</title>
		<link>http://www.khelll.com/blog/ruby/stackoverflow-cool-ruby-questions-4/</link>
		<comments>http://www.khelll.com/blog/ruby/stackoverflow-cool-ruby-questions-4/#comments</comments>
		<pubDate>Tue, 16 Mar 2010 23:21:41 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Stackoverflow]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=623</guid>
		<description><![CDATA[Welcome to the fourth post of this series.  Just before proceeding to the questions, I would like to mention the great Metaprogramming Ruby: Program Like the Ruby Pros book by Paolo Perrotta, a very good book that explains the metaprogramming aspects of the Ruby language.
Now let&#8217;s get going!
Scope gates
Taken from the above mentioned book:
There [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to the fourth post of this <a href="http://www.khelll.com/blog/category/stackoverflow/">series</a>.  Just before proceeding to the questions, I would like to mention the great<a href="http://www.pragprog.com/titles/ppmetr/metaprogramming-ruby"> Metaprogramming Ruby: Program Like the Ruby Pros</a> book by Paolo Perrotta, a very good book that explains the metaprogramming aspects of the Ruby language.<br />
Now let&#8217;s get going!</p>
<h2>Scope gates</h2>
<p>Taken from the above mentioned book:</p>
<blockquote><p>There are exactly three places where a program leaves the previous scope behind and opens a new one:<br />
• Class definitions • Module definitions • Methods<br />
Scope changes whenever the program enters (or exits) a class or module definition or a method. These three borders are marked by the keywords class, module, and def, respectively. Each of these keywords acts like a Scope Gate.</p></blockquote>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/2289680/closure-doesnt-work">Closure doesn’t work</a></p>
<p><strong>The question text is</strong>:<br />
If block is a closure, why this code does not work? And how to make it work?</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"> <span style="color:#9966CC; font-weight:bold;">def</span> R<span style="color:#006600; font-weight:bold;">&#40;</span>arg<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">Class</span>.<span style="color:#9900CC;">new</span> <span style="color:#9966CC; font-weight:bold;">do</span>
        <span style="color:#9966CC; font-weight:bold;">def</span> foo
           <span style="color:#CC0066; font-weight:bold;">puts</span> arg
        <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> A <span style="color:#006600; font-weight:bold;">&lt;</span> R<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;Hello!&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
A.<span style="color:#9900CC;">new</span>.<span style="color:#9900CC;">foo</span> <span style="color:#008000; font-style:italic;">#throws undefined local variable or method `arg' for #&lt;A:0x2840538&gt;</span></pre></div></div>

<p><strong>The answer is</strong>:<br />
Blocks are closures and arg is indeed available inside the <code>Class.new</code> block. It&#8217;s just not available inside the <code>foo</code> method because def starts a new scope. If you replace <code>def</code> with <code>define_method</code>, which takes a block, you&#8217;ll see the result you want:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> R<span style="color:#006600; font-weight:bold;">&#40;</span>arg<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">Class</span>.<span style="color:#9900CC;">new</span> <span style="color:#9966CC; font-weight:bold;">do</span>
        define_method<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:foo</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
           <span style="color:#CC0066; font-weight:bold;">puts</span> arg
        <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> A <span style="color:#006600; font-weight:bold;">&lt;</span> R<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;Hello!&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
A.<span style="color:#9900CC;">new</span>.<span style="color:#9900CC;">foo</span> <span style="color:#008000; font-style:italic;"># Prints: Hello!</span></pre></div></div>

<h2>Almost everything in Ruby is an object</h2>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/416047/examples-of-things-that-are-not-objects-in-ruby">Examples of ‘Things’ that are not Objects in Ruby</a></p>
<p><strong>The question text is</strong>:<br />
&#8220;Everything is an object&#8221; was one of the first things I learned about Ruby, but in Peter Cooper&#8217;s Beginning Ruby: From Novice to Professional book, it is mentioned that &#8220;<strong>almost</strong> everything in Ruby is an object&#8221;.</p>
<p>Can you give me some <strong>examples of things that are not objects in Ruby</strong>?</p>
<p><strong>The answer is</strong>:<br />
he most obvious one that jumps into my head would be blocks. Blocks can be easily reified to a Proc object, either by using the &#038;block parameter form in a parameter list or by using lambda, proc, Proc.new or (in Ruby 1.9) the &#8220;stabby lambda&#8221; syntax. But on its own, they aren&#8217;t objects.</p>
<p>Another example are built in operators: while methods are objects, some operators are not implemented as methods (and, or &#038;&#038;, ||), so those operators aren&#8217;t objects.</p>
<h2>Hash keys</h2>
<p>The idea here is that whenever you want to define your own keys types for Ruby hashes, then you need to define 2 methods <a href="http://ruby-doc.org/core/classes/Object.html#M000347">#eq?</a> and <a href="http://ruby-doc.org/core/classes/Object.html#M000337">#hash</a> for those types.</p>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/2328685/how-to-make-object-instance-a-hash-key-in-ruby">How to make object instance a hash key in Ruby?</a></p>
<p><strong>The question text is</strong>:<br />
I have a class Foo with a few member variables. When all values in two instances of the class are equal I want the objects to be &#8216;equal&#8217;. I&#8217;d then like these objects to be keys in my hash. When I currently try this, the hash treats each instance as unequal.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">h = <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
f1 = Foo.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span>a,b<span style="color:#006600; font-weight:bold;">&#41;</span>
f2 = Foo.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span>a,b<span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>f1 and f2 should be equal at this point.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">h<span style="color:#006600; font-weight:bold;">&#91;</span>f1<span style="color:#006600; font-weight:bold;">&#93;</span> = <span style="color:#006666;">7</span>
h<span style="color:#006600; font-weight:bold;">&#91;</span>f2<span style="color:#006600; font-weight:bold;">&#93;</span> = <span style="color:#006666;">8</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> h<span style="color:#006600; font-weight:bold;">&#91;</span>f1<span style="color:#006600; font-weight:bold;">&#93;</span></pre></div></div>

<p>should print 8</p>
<p><strong>The answer is</strong>:<br />
See <a href="http://ruby-doc.org/core/classes/Hash.html">http://ruby-doc.org/core/classes/Hash.html</a></p>
<blockquote><p> Hash uses key.eql? to test keys for equality. If you need to use instances of your own classes as keys in a Hash, it is recommended that you define both the eql? and hash methods. The hash method must have the property that a.eql?(b) implies a.hash == b.hash.</p></blockquote>
<p>The eql? method is easy to implement: return true if all member variables are the same. For the hash method, use [@data1, @data2].hash</p>
<h2>Kernel#abort</h2>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/29539/ruby-exit-message">Ruby &#8211; Exit Message</a></p>
<p><strong>The question text is</strong>:<br />
Is there a one line function call that quits the program and displays a message? I know in Perl its as simple as this:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">die<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;Message goes here&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>Essentially I&#8217;m just tired of typing this:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;Message goes here&quot;</span>
<span style="color:#CC0066; font-weight:bold;">exit</span></pre></div></div>

<p><strong>The answer is</strong>:<br />
The &#8216;abort&#8217; function does this. For example:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">abort<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;Message goes here&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.khelll.com/blog/ruby/stackoverflow-cool-ruby-questions-4/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>StackOverflow cool Ruby questions 3</title>
		<link>http://www.khelll.com/blog/ruby/stackoverflow-cool-ruby-questions-3/</link>
		<comments>http://www.khelll.com/blog/ruby/stackoverflow-cool-ruby-questions-3/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 17:02:31 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Stackoverflow]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=611</guid>
		<description><![CDATA[Welcome to the third post of this ]]></description>
			<content:encoded><![CDATA[<p>Welcome to the third post of this <a href=http://www.khelll.com/blog/category/stackoverflow/">series</a>.  Just before diving into the new questions&#8217; set, I want to mention a little <a href="http://gist.github.com/255479">script</a> that I wrote to notify the user when a new question is posted on Stackoverflow, it works on Mac and uses growl.<br />
Now let&#8217;s proceed to questions:</p>
<h2>Relationship between the metaclass of base and derived classes</h2>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/2137853/what-is-the-relationship-between-the-metaclass-of-base-and-derived-class-in-ruby">What is the relationship between the metaclass of Base and Derived class in Ruby?</a></p>
<p><strong>The question text is</strong>:</p>
<p>In Ruby, we could use <code>super</code> within singleton method to call the corresponding super class&#8217;s singleton method, like the following code shows.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Base
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">class_method</span>
    <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;Base class method&quot;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> Derived <span style="color:#006600; font-weight:bold;">&lt;</span> Base
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">class_method</span>
    <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;Derived class method&quot;</span>
    <span style="color:#9966CC; font-weight:bold;">super</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
Derived.<span style="color:#9900CC;">class_method</span>
<span style="color:#008000; font-style:italic;"># Derived class method</span>
<span style="color:#008000; font-style:italic;"># Base class method</span></pre></div></div>

<p>However, I don&#8217;t seem quite get how that call to <code>super</code> within <code>Derived.class_method</code> could reach <code>Base.class_method</code>. I&#8217;d assume that <code>class_method</code> is defined on their metaclass, does that mean their metaclass has parent/child relationship? (I can&#8217;t quite confirm that by experiments)</p>
<p>I&#8217;m asking this question because I remembered seeing somewhere there&#8217;s some kind of relationship between base and derived class&#8217; metaclass (but I can&#8217;t find it any more). In addition to know how actually <code>super</code> works, I&#8217;d also like to confirm whether the two metaclasses are totally separate or not.</p>
<p><strong>The answer is</strong>:<br />
There are four class objects in play here:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&lt;</span>Class<span style="color:#006600; font-weight:bold;">&gt;---</span>class<span style="color:#006600; font-weight:bold;">---&gt;&lt;</span>Class<span style="color:#006600; font-weight:bold;">&gt;</span>
Base               <span style="color:#008000; font-style:italic;">#Base</span>
   ^                  ^
   <span style="color:#006600; font-weight:bold;">|</span>                  <span style="color:#006600; font-weight:bold;">|</span>
   <span style="color:#006600; font-weight:bold;">|</span>                  <span style="color:#006600; font-weight:bold;">|</span>
 <span style="color:#9966CC; font-weight:bold;">super</span>              <span style="color:#9966CC; font-weight:bold;">super</span>
   <span style="color:#006600; font-weight:bold;">|</span>                  <span style="color:#006600; font-weight:bold;">|</span>
   <span style="color:#006600; font-weight:bold;">|</span>                  <span style="color:#006600; font-weight:bold;">|</span>
<span style="color:#006600; font-weight:bold;">&lt;</span>Class<span style="color:#006600; font-weight:bold;">&gt;</span>            <span style="color:#006600; font-weight:bold;">&lt;</span>Class<span style="color:#006600; font-weight:bold;">&gt;</span>
Derived<span style="color:#006600; font-weight:bold;">---</span>class<span style="color:#006600; font-weight:bold;">---&gt;</span><span style="color:#008000; font-style:italic;">#Derived</span></pre></div></div>

<p>Nomenclature:</p>
<ul>
<li><...> is the class of each object.</li>
<li>The name of the class is on the second line.</li>
<li>If the name starts with #, it&#8217;s the eigenclass (aka singleton class).</li>
<li>super points to a class&#8217;s superclass</li>
<li>class points to the class&#8217;s class.</li>
</ul>
<p>When you call Derived.class_method, Ruby follows the &#8220;right one and then up&#8221; rule: First go to the object&#8217;s class, then follow the superclass chain up, stopping when the method is found:</p>
<ul>
<li>The receiver of the &#8220;class_method&#8221; call is Derived. So follow the chain right to Derived&#8217;s class object, which is its eigenclass (#Derived).</li>
<li>  #Derived does not define the method, so Ruby follows the chain up the chain to #Derived&#8217;s superclass, which is #Base.</li>
<li>    The method is found there, so Ruby dispatches the message to #Base.class_method</li>
</ul>
<p>You don&#8217;t think I knew all this stuff off the top of my head, did you? Here&#8217;s where my brain got all this meta juju: <a href="http://pragprog.com/titles/ppmetr/metaprogramming-ruby">Metaprogramming Ruby</a>.</p>
<p><strong>Part 2.</strong> How to make an &#8220;eigenclass&#8221; (aka &#8220;singleton class&#8221;) come out of hiding</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#CC00FF; font-weight:bold;">Object</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> eigenclass
    <span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> <span style="color:#0000FF; font-weight:bold;">self</span>
      <span style="color:#0000FF; font-weight:bold;">self</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>This method will return the eigenclass of any object. Now, what about classes? Those are objects, too.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">p</span> Derived.<span style="color:#9900CC;">eigenclass</span>               <span style="color:#008000; font-style:italic;"># =&gt; #&lt;Class:Derived&gt;</span>
<span style="color:#CC0066; font-weight:bold;">p</span> Derived.<span style="color:#9900CC;">eigenclass</span>.<span style="color:#9900CC;">superclass</span>    <span style="color:#008000; font-style:italic;"># =&gt; #&lt;Class:Base&gt;</span>
<span style="color:#CC0066; font-weight:bold;">p</span> Base.<span style="color:#9900CC;">eigenclass</span>                  <span style="color:#008000; font-style:italic;"># =&gt; #&lt;Class:Base&gt;</span></pre></div></div>

<p>Note: Above is from Ruby1.9. When run under Ruby 1.8, you get a surprise:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">p</span> Derived.<span style="color:#9900CC;">eigenclass</span>.<span style="color:#9900CC;">superclass</span>    <span style="color:#008000; font-style:italic;"># =&gt; #&lt;Class:Class&gt;</span></pre></div></div>

<h2>Idiomatic object creation</h2>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/1778638/idiomatic-object-creation-in-ruby">Idiomatic object creation in ruby</a></p>
<p><strong>The question text is</strong>:</p>
<p>In ruby, I often find myself writing the following:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Foo
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize<span style="color:#006600; font-weight:bold;">&#40;</span>bar, baz<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0066ff; font-weight:bold;">@bar</span> = bar
    <span style="color:#0066ff; font-weight:bold;">@baz</span> = baz
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> more stuff <span style="color:#006600; font-weight:bold;">&gt;&gt;</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>or even</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Foo
  attr_accessor <span style="color:#ff3333; font-weight:bold;">:bar</span>, <span style="color:#ff3333; font-weight:bold;">:baz</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize<span style="color:#006600; font-weight:bold;">&#40;</span>bar, baz<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0066ff; font-weight:bold;">@bar</span> = bar
    <span style="color:#0066ff; font-weight:bold;">@baz</span> = baz
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> more stuff <span style="color:#006600; font-weight:bold;">&gt;&gt;</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>I&#8217;m always keen to minimize boilerplate as much as possible &#8211; so is there a more idiomatic way of creating objects in ruby?</p>
<p><strong>The answer is:</strong></p>
<p>Struct objects are classes which do almost what you want. The only difference is, the initialize method has nil as default value for all it&#8217;s arguments. You use it like this</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">A= <span style="color:#CC00FF; font-weight:bold;">Struct</span>.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:a</span>, <span style="color:#ff3333; font-weight:bold;">:b</span>, <span style="color:#ff3333; font-weight:bold;">:c</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>or</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> A <span style="color:#006600; font-weight:bold;">&lt;</span> Struc.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:a</span>, <span style="color:#ff3333; font-weight:bold;">:b</span>, <span style="color:#ff3333; font-weight:bold;">:c</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p><em>Struct has one big drawback. You can not inherit from another class.</em></p>
<h2>Block vs brackets</h2>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/2122380/using-do-block-vs-brackets">Using do block vs brackets {}</a></p>
<p><strong>The question text is</strong>:</p>
<p>New to ruby, put on your newbie gloves.</p>
<p>Is there any difference (obscure or practical) between the following two snippets?</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">my_array = <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:uno</span>, <span style="color:#ff3333; font-weight:bold;">:dos</span>, <span style="color:#ff3333; font-weight:bold;">:tres</span><span style="color:#006600; font-weight:bold;">&#93;</span>
my_array.<span style="color:#9900CC;">each</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#006600; font-weight:bold;">|</span>item<span style="color:#006600; font-weight:bold;">|</span> 
    <span style="color:#CC0066; font-weight:bold;">puts</span> item
<span style="color:#006600; font-weight:bold;">&#125;</span>
&nbsp;
my_array = <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:uno</span>, <span style="color:#ff3333; font-weight:bold;">:dos</span>, <span style="color:#ff3333; font-weight:bold;">:tres</span><span style="color:#006600; font-weight:bold;">&#93;</span>
my_array.<span style="color:#9900CC;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>item<span style="color:#006600; font-weight:bold;">|</span> 
    <span style="color:#CC0066; font-weight:bold;">puts</span> item
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>I realize the bracket syntax would allow you to place the block on one line</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">my_array.<span style="color:#9900CC;">each</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#006600; font-weight:bold;">|</span>item<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#CC0066; font-weight:bold;">puts</span> item <span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

<p>but outside of that are there any compelling reasons to use one syntax over the other?</p>
<p><strong>The  answer is:</strong></p>
<p><a href="http://rads.stackoverflow.com/amzn/click/0596523696">Ruby cookbook</a> says bracket syntax has higher precedence order than <code>do..end</code><br />
Keep in mind that the bracket syntax has a higher precedence than the do..end syntax. Consider the following two snippets of code:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">1.<span style="color:#9900CC;">upto</span> <span style="color:#006666;">3</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span>
  <span style="color:#CC0066; font-weight:bold;">puts</span> x
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
1.<span style="color:#9900CC;">upto</span> <span style="color:#006666;">3</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#CC0066; font-weight:bold;">puts</span> x <span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#008000; font-style:italic;"># SyntaxError: compile error</span></pre></div></div>

<p>Second example only works when parentheses is used, <code>1.upto(3) { |x| puts x }</code></p>
<h2>String and whitespace</h2>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/2130676/see-if-a-ruby-string-has-whitespace-in-it">See if a ruby string has whitespace in it</a></p>
<p><strong>The question text is</strong>:</p>
<p>I want to see if a string has any white space in it. What&#8217;s the most effective way of doing this in ruby?</p>
<p>Thanks</p>
<p><strong>The  answer is:</strong></p>
<p>If by &#8220;white space&#8221; you mean in the Regular Expression sense, which is any of space character, tab, newline, carriage return or (I think) form-feed, then any of the answers provided will work:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">s.<span style="color:#9900CC;">match</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">/</span>\s<span style="color:#006600; font-weight:bold;">/</span><span style="color:#006600; font-weight:bold;">&#41;</span>
s.<span style="color:#9900CC;">index</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">/</span>\s<span style="color:#006600; font-weight:bold;">/</span><span style="color:#006600; font-weight:bold;">&#41;</span>
s =~ <span style="color:#006600; font-weight:bold;">/</span>\s<span style="color:#006600; font-weight:bold;">/</span>
s<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">/</span>\s<span style="color:#006600; font-weight:bold;">/</span><span style="color:#006600; font-weight:bold;">&#93;</span></pre></div></div>

<h2>Index of the largest value in an array</h2>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/2149802/in-ruby-what-is-the-cleanest-way-of-obtaining-the-index-of-the-largest-value-in">In Ruby, what is the cleanest way of obtaining the index of the largest value in an array? </a></p>
<p><strong>The question text is</strong>:</p>
<p>If a is the array, I want a.index(a.max), but something more Ruby-like. It should be obvious, but I&#8217;m having trouble finding the answer at so and elsewhere. Obviously, I am new to Ruby.</p>
<p><strong>The  answer is:</strong></p>
<p>For Ruby 1.8.7 or above:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">a.<span style="color:#9900CC;">each_with_index</span>.<span style="color:#9900CC;">max</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#93;</span></pre></div></div>

<p>It does one iteration. Not entirely the most semantic thing ever, but if you find yourself doing this a lot, I would wrap it in an index_of_max method anyway.</p>
<p><code>each_with_index</code> without a block returns an enumerator that gives the item and its index. We then send <code>max</code> to this enumerator, which does the standard <code>max</code> algorithm on item-index pairs. <code>Array.<=></code> is implemented so that the first item determines the ordering (unless there&#8217;s a tie, in which case the second is compared, and so on), so this works basically the same as doing <code>max</code> on an array of the values themselves. Then to get the index, we ask for the second item of the result (since we got a series of <code>[value, index]</code> pairs from <code>each_with_index</code>)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.khelll.com/blog/ruby/stackoverflow-cool-ruby-questions-3/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>StackOverflow cool Ruby questions 2</title>
		<link>http://www.khelll.com/blog/ruby/stackoverflow-cool-ruby-questions-2/</link>
		<comments>http://www.khelll.com/blog/ruby/stackoverflow-cool-ruby-questions-2/#comments</comments>
		<pubDate>Sat, 17 Oct 2009 15:58:44 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Stackoverflow]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=587</guid>
		<description><![CDATA[Welcome in this second post of this series. Just before I list the questions of this one, I want to mention 2 things:

You can follow StackOverflow tagged Ruby questions on twitter using the user: sof_ruby 
Some ppl feel shy to ask or even to answer, my (little) experience in life taught me that If you [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome in this second post of this <a href="http://www.khelll.com/blog/category/stackoverflow/">series</a>. Just before I list the questions of this one, I want to mention 2 things:</p>
<ul>
<li>You can follow StackOverflow tagged Ruby questions on twitter using the user: <a href="http://twitter.com/sof_ruby">sof_ruby</a> </li>
<li>Some ppl feel shy to ask or even to answer, my (little) experience in life taught me that If you don&#8217;t ask, you don&#8217;t learn. If you don&#8217;t participate, you don&#8217;t learn. On the other side that&#8217;s the benefit of pair programming, ain&#8217;t it?</li>
</ul>
<p>Now let&#8217;s proceed to questions:</p>
<h2>Hash Autovivification</h2>
<p>Hash Autovivication in simple words is the ability to do things like:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">a=<span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
a<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">'b'</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">'c'</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">'d'</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">'e'</span><span style="color:#006600; font-weight:bold;">&#93;</span>=<span style="color:#996600;">'f'</span></pre></div></div>

<p>The cool idea here is that all intermediate-level hashs will be created automatically.<br />
We can&#8217;t do that directly in Ruby, a statement like the previous one will issue an error : <code>NoMethodError: undefined method `[]' for nil:NilClass<br />
</code></p>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/1485186/instance-eval-within-block">ruby hash autovivification (facets)</a></p>
<p><strong>The question text is</strong>:<br />
Here is a clever trick to enable hash autovivification in ruby (taken from facets):</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># Monkey patching Hash class:</span>
<span style="color:#008000; font-style:italic;"># File lib/core/facets/hash/autonew.rb, line 19</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">autonew</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">*</span>args<span style="color:#006600; font-weight:bold;">&#41;</span>
    leet = <span style="color:#CC0066; font-weight:bold;">lambda</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#006600; font-weight:bold;">|</span>hsh, key<span style="color:#006600; font-weight:bold;">|</span> hsh<span style="color:#006600; font-weight:bold;">&#91;</span>key<span style="color:#006600; font-weight:bold;">&#93;</span> = new<span style="color:#006600; font-weight:bold;">&#40;</span> <span style="color:#006600; font-weight:bold;">&amp;</span>leet <span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#125;</span>
    new<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">*</span>args,<span style="color:#006600; font-weight:bold;">&amp;</span>leet<span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Although it works (of course), I find it really frustrating that I can&#8217;t figure out how this two liner does what it does.</p>
<p><strong>The answer is</strong>:<br />
The standard <a href="http://ruby-doc.org/core/classes/Hash.html#M002840">new method for Hash</a> accepts a block. This block is called in the event of trying to access a key in the Hash which does not exist. The block is passed the Hash itself and the key that was requested (the two parameters) and should return the value that should be returned for the requested key.</p>
<p>You will notice that the leet lambda does 2 things. It returns a new Hash with leet itself as the block for handling defaults. This is the behaviour which allows autonew to work for Hashes of arbitrary depth. It also assigns this new Hash to hsh[key] so that next time you request the same key you will get the existing Hash rather than a new one being created.</p>
<p>So:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">a = <span style="color:#CC00FF; font-weight:bold;">Hash</span>.<span style="color:#9900CC;">autonew</span>
a<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">'b'</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">'c'</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">'d'</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">'e'</span><span style="color:#006600; font-weight:bold;">&#93;</span>=<span style="color:#996600;">'f'</span> <span style="color:#008000; font-style:italic;">#=&gt; &quot;f&quot;</span>
a.<span style="color:#9900CC;">inspect</span> <span style="color:#008000; font-style:italic;">#=&gt; {&quot;b&quot;=&gt;{&quot;c&quot;=&gt;{&quot;d&quot;=&gt;{&quot;e&quot;=&gt;&quot;f&quot;}}}}</span></pre></div></div>

</ul>
<h2>Class instance variables</h2>
<p>This answer of this one is easy, but the idea of <strong>Class instance variables</strong> is what matters.</p>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/1548661/total-newbie-instance-variables-in-ruby">Total newbie: Instance variables in ruby?</a></p>
<p><strong>The question text is</strong>:<br />
Pardon the total newbiew question but why is <code>@game_score</code> always nil?</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Bowling
  <span style="color:#0066ff; font-weight:bold;">@game_score</span> = <span style="color:#006666;">0</span>
    <span style="color:#9966CC; font-weight:bold;">def</span> hit<span style="color:#006600; font-weight:bold;">&#40;</span>pins<span style="color:#006600; font-weight:bold;">&#41;</span>
        <span style="color:#0066ff; font-weight:bold;">@game_score</span> = <span style="color:#0066ff; font-weight:bold;">@game_score</span> <span style="color:#006600; font-weight:bold;">+</span> pins
    <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
    <span style="color:#9966CC; font-weight:bold;">def</span> score
        <span style="color:#0066ff; font-weight:bold;">@game_score</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p><strong>The answer is</strong>:<br />
Because you don&#8217;t have</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> initialize
  <span style="color:#0066ff; font-weight:bold;">@game_score</span> = <span style="color:#006666;">0</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>The assignment in the class definition is not doing what you think it is doing, and when <code>hit</code> gets invoked it can&#8217;t add to <code>nil</code>.<br />
If you now ask what happened to <code>@game_score</code>?, well, always remember Class is an object and Object is a class.<br />
It&#8217;s way cool the way Ruby classes have this Zen-like &#8220;real&#8221; existence. Ruby doesn&#8217;t precisely have named classes, rather, class names are references to objects of class <code>Class</code>. <strong>By assigning to <code>@game_score</code> outside of an instance method you created a class instance variable, an attribute of the class object <code>Bowling</code>, which is an instance of class <code>Class</code></strong>. These objects are not, in general, very useful. (See Chapter 1, The Ruby Way, Hal Fulton.)</p>
<p>You can reach the @game_score class instance variable by doing this:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> Bowling
  attr_accessor <span style="color:#ff3333; font-weight:bold;">:game_score</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
Bowling.<span style="color:#9900CC;">game_score</span> <span style="color:#008000; font-style:italic;">#=&gt; 0</span>
Bowling.<span style="color:#9900CC;">game_score</span> = <span style="color:#006666;">6</span> <span style="color:#008000; font-style:italic;">#=&gt; 6</span></pre></div></div>

<p><strong>(A question for you: What is the difference between class variables and class instance variables?)</strong></p>
<h2>Creating data structures in Ruby</h2>
<p>I have committed a mistake myself in answering this question <img src='http://www.khelll.com/blog/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> , however remember: If you don&#8217;t try, you don&#8217;t learn.</p>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/1571349/can-the-array-be-reinvented-in-ruby">Can the array be reinvented in Ruby?</a></p>
<p><strong>The question text is</strong>:<br />
This is just a hypothetical question, if you wouldn&#8217;t have the <code>Array</code> and the <code>Hash</code> class, would there be any way of implementing an Array class in pure Ruby? How?</p>
<p><strong>The answer is</strong>:<br />
Yes we can:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> MyArray
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#CC00FF; font-weight:bold;">Enumerable</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize
    <span style="color:#0066ff; font-weight:bold;">@size</span> = <span style="color:#006666;">0</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#006600; font-weight:bold;">&lt;&lt;</span><span style="color:#006600; font-weight:bold;">&#40;</span>val<span style="color:#006600; font-weight:bold;">&#41;</span>
    instance_variable_set<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;@a#{@size}&quot;</span>.<span style="color:#9900CC;">to_sym</span>, val<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0066ff; font-weight:bold;">@size</span> <span style="color:#006600; font-weight:bold;">+</span>= <span style="color:#006666;">1</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#40;</span>n<span style="color:#006600; font-weight:bold;">&#41;</span>
    instance_variable_get<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;@a#{n}&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> length
    <span style="color:#0066ff; font-weight:bold;">@size</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> each
    0.<span style="color:#9900CC;">upto</span><span style="color:#006600; font-weight:bold;">&#40;</span>@size <span style="color:#006600; font-weight:bold;">-</span> <span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#006600; font-weight:bold;">|</span>n<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#9966CC; font-weight:bold;">yield</span> <span style="color:#0000FF; font-weight:bold;">self</span><span style="color:#006600; font-weight:bold;">&#91;</span>n<span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#006600; font-weight:bold;">&#125;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
a = MyArray.<span style="color:#9900CC;">new</span>
a <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> <span style="color:#006666;">1</span>
a <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> <span style="color:#006666;">2</span>
<span style="color:#CC0066; font-weight:bold;">p</span> a.<span style="color:#9900CC;">to_a</span>     <span style="color:#008000; font-style:italic;">#=&gt; [1,2]</span></pre></div></div>

<p>This works by creating instance variables <code>@a0</code>, <code>@a1</code>, etc. on the object to represent array indices 0, 1, etc. It has constant time length and index operations. The rest of the operations (remove, etc.) are a bit more effort to implement, but it&#8217;s absolutely possible.</p>
<p>Note that the constant time property for the index operation depends on the underlying Ruby runtime using an appropriate data structure for instance variables.</p>
<h2>Hash#reject</h2>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/1531047/update-attributes-unless-blank">Update attributes unless blank?</a></p>
<p><strong>The question text is</strong>:<br />
I have an existing Project record, and I&#8217;m importing a CSV file to update the associated Project attributes. However, often the CSV will contain blank fields and I don&#8217;t want to overright exisiting attributes if the related CSV field is blank.</p>
<p>Something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">project.<span style="color:#9900CC;">update_attributes</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:name</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> row.<span style="color:#9900CC;">field</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'project_name'</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">unless</span> row.<span style="color:#9900CC;">field</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'project_name'</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">blank</span>?,                                                                         
                          <span style="color:#ff3333; font-weight:bold;">:owner</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> row.<span style="color:#9900CC;">field</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'project_owner'</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">unless</span> row.<span style="color:#9900CC;">field</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'project_owner'</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">blank</span>?,
                          <span style="color:#ff3333; font-weight:bold;">:due_date</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> row.<span style="color:#9900CC;">field</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'project_due_date'</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">unless</span> row.<span style="color:#9900CC;">field</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'project_due_date'</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">blank</span>?<span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p><strong>The answer is:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">project.<span style="color:#9900CC;">update_attributes</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#123;</span>:name <span style="color:#006600; font-weight:bold;">=&gt;</span> row.<span style="color:#9900CC;">field</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'project_name'</span><span style="color:#006600; font-weight:bold;">&#41;</span>,                                                                         
                          <span style="color:#ff3333; font-weight:bold;">:owner</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> row.<span style="color:#9900CC;">field</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'project_owner'</span><span style="color:#006600; font-weight:bold;">&#41;</span>,
                          <span style="color:#ff3333; font-weight:bold;">:due_date</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> row.<span style="color:#9900CC;">field</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'project_due_date'</span><span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#125;</span>.<span style="color:#9900CC;">reject</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>k,v<span style="color:#006600; font-weight:bold;">|</span> v.<span style="color:#9900CC;">blank</span>?<span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<h2>Ruby &#8216;private&#8217; behavior</h2>
<p>The key point here to remember is that <code>private</code>, <code>protected</code> and <code>pulbic</code></a> are just other methods defined in Ruby <a href="http://www.ruby-doc.org/core/classes/Module.html">Module</a> class.</p>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/1565269/are-there-good-reasons-for-private-to-work-the-way-it-does-in-ruby">Are there good reasons for ‘private’ to work the way it does in Ruby?</a></p>
<p><strong>The question text is</strong>:<br />
It took me a while to understand how private methods work in Ruby, and it really strikes me as being very awkward. Does anyone know if there are good reasons for private methods to be handled the way they are? Is it just historic reasons? Or implementation reasons? Or are there good solid logical reasons (ie. semantic)?</p>
<p>For example:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Person
  private
  attr_reader <span style="color:#ff3333; font-weight:bold;">:weight</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> Spy <span style="color:#006600; font-weight:bold;">&lt;</span> Person
 private
  attr_accessor <span style="color:#ff3333; font-weight:bold;">:code</span>
 public
  <span style="color:#9966CC; font-weight:bold;">def</span> test
    code          <span style="color:#008000; font-style:italic;">#(1) OK: you can call a private method in self</span>
    Spy.<span style="color:#9900CC;">new</span>.<span style="color:#9900CC;">code</span>  <span style="color:#008000; font-style:italic;">#(2) ERROR: cannot call a private method on any other object</span>
    <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">code</span>     <span style="color:#008000; font-style:italic;">#(3) ERROR!!! cannot call a private method explicitly on 'self'</span>
    code=<span style="color:#996600;">&quot;xyz&quot;</span>    <span style="color:#008000; font-style:italic;">#(4) Ok, it runs, but it actually creates a local variable!!!</span>
    <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">code</span>=<span style="color:#996600;">&quot;z&quot;</span> <span style="color:#008000; font-style:italic;">#(5) OK! This is the only case where explicit 'self' is ok</span>
    weight        <span style="color:#008000; font-style:italic;">#(6) OK! You can call a private method defined in a base class</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<ul>
<li>Ruby&#8217;s behaviour on lines (1), (2) and (5) seems reasonable.</li>
<li>The fact that (6) is ok is a bit strange, especially coming from Java and C++. Any good reason for this?</li>
<li>I really do not understand why (3) fails ! An explanation, anyone?</li>
<li>The problem on line (4) looks like an ambiguity in the grammar, which has nothing to do with &#8216;private&#8217;.</li>
<p>Any ideas?
</ul>
<p><strong>The  answer is:</strong></p>
<p>You might find it helpful to read ruby&#8217;s <a href="http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut%5Fclasses.html">definition of public, private and protected</a> <strong>(Skip to Access Control)<br />
</strong><br />
Ruby&#8217;s private is analogous to Java&#8217;s protected. There is no Ruby equivalent of Java&#8217;s private. But there are ways to fake it.</p>
<p>Private is defined as methods/variables that can <strong>only</strong> be called implicitly. This is why statements 2 and 3 fail. In other words, private limits methods/variables to the context of a class or subclass in which they are defined. Inheritance passes private methods to the subclasses and can therefore be accessed with an implicit self. (Explaining why statement 6 works.)</p>
<p>I think you&#8217;re looking for something closer to protected. Which behaves similarly to Java accessors that are not given a visibility (eg: public, private, protected) By changing the private in Spy to protected all 6 of your statements work. Protected methods can be called by any instance of the defining class or their subclasses. Either explicitly or implicitly called on self are valid statements for protected methods so long as the caller is either the class of the object responding to the call, or inherits from it.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Person
  private
  attr_reader <span style="color:#ff3333; font-weight:bold;">:weight</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> Spy <span style="color:#006600; font-weight:bold;">&lt;</span> Person
 protected
  attr_accessor <span style="color:#ff3333; font-weight:bold;">:code</span>
 public
  <span style="color:#9966CC; font-weight:bold;">def</span> test
    code          <span style="color:#008000; font-style:italic;">#(1) OK: you can call a private method in self</span>
    Spy.<span style="color:#9900CC;">new</span>.<span style="color:#9900CC;">code</span>  <span style="color:#008000; font-style:italic;">#(2) OK: Calling protected method on another instance from same class family or a descendant.</span>
    <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">code</span>     <span style="color:#008000; font-style:italic;">#(3) OK: Calling protected method on with explicit self is allowed with protected</span>
    code=<span style="color:#996600;">&quot;xyz&quot;</span>    <span style="color:#008000; font-style:italic;">#(4) Ok, it runs, but it actually creates a local variable!!!</span>
    <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">code</span>=<span style="color:#996600;">&quot;z&quot;</span> <span style="color:#008000; font-style:italic;">#(5) OK! This is the only case where explicit 'self' is ok</span>
    weight        <span style="color:#008000; font-style:italic;">#(6) OK! You can call a private method defined in a base class</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
s = Spy.<span style="color:#9900CC;">new</span>
s.<span style="color:#9900CC;">test</span> <span style="color:#008000; font-style:italic;"># succeeds</span>
s.<span style="color:#9900CC;">code</span> <span style="color:#008000; font-style:italic;">#(7) Error: Calling protected method outside of the class or its descendants.</span></pre></div></div>

<p>As for statement 4. You are correct in assuming this is to avoid ambiguity. It&#8217;s more a safeguard to the potential harm of ruby&#8217;s dynamic nature. It ensures that you cannot override accessors by opening up the class again later. A situation that can arise, for example by eval&#8217;ing tainted code.</p>
<p>I can only speculate on he design decisions that led to these behaviours. For most of it I feel it comes down to the dynamic nature of the language.</p>
<p>P.S. If you really want to give things the java definition of private. Only available to the class in which it&#8217;s defined, not even subclasses. You could add an self.inherited method to your classes to remove references to the methods you want to limit access to.</p>
<p>Making the weight attribute inaccessible from subclasses:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Person
  private
  attr_reader <span style="color:#ff3333; font-weight:bold;">:weight</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize
    <span style="color:#0066ff; font-weight:bold;">@weight</span> = <span style="color:#006666;">5</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">inherited</span><span style="color:#006600; font-weight:bold;">&#40;</span>subclass<span style="color:#006600; font-weight:bold;">&#41;</span>
    subclass.<span style="color:#9900CC;">send</span> <span style="color:#ff3333; font-weight:bold;">:undef_method</span>, <span style="color:#ff3333; font-weight:bold;">:weight</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> Spy <span style="color:#006600; font-weight:bold;">&lt;</span> Person
 private
  attr_accessor <span style="color:#ff3333; font-weight:bold;">:code</span>
 public
  <span style="color:#9966CC; font-weight:bold;">def</span> test
     weight       
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
Person.<span style="color:#9900CC;">new</span>.<span style="color:#9900CC;">send</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:weight</span><span style="color:#006600; font-weight:bold;">&#41;</span>  <span style="color:#008000; font-style:italic;"># =&gt; 5</span>
Spy.<span style="color:#9900CC;">new</span>.<span style="color:#9900CC;">send</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:weight</span><span style="color:#006600; font-weight:bold;">&#41;</span>  <span style="color:#008000; font-style:italic;">#=&gt; Unhelpful undefined method error</span></pre></div></div>

<p>It may make more sense to replace the undef_method call to something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">inherited</span><span style="color:#006600; font-weight:bold;">&#40;</span>subclass<span style="color:#006600; font-weight:bold;">&#41;</span>
    subclass.<span style="color:#9900CC;">class_eval</span> <span style="color:#006600; font-weight:bold;">%</span><span style="color:#006600; font-weight:bold;">&#123;</span>
      <span style="color:#9966CC; font-weight:bold;">def</span> weight 
        <span style="color:#CC0066; font-weight:bold;">raise</span> <span style="color:#996600;">&quot;Private method called from subclass. Access Denied&quot;</span>
      <span style="color:#9966CC; font-weight:bold;">end</span>
     <span style="color:#006600; font-weight:bold;">&#125;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Which provides a much more helpful error and the same functionality.</p>
<p>The send is necessary to get around calling private methods for other classes. Only used to prove that things are actually working.</p>
<p>Which in hindsight, makes private and protected useless. If you&#8217;re really serious about protecting your methods you will have to override send to block them. You could also make send private.</p>
<p>It ends up being one of those &#8220;Damned if you do, damned if you don&#8217;t&#8221; situations. There are legitimate uses of calling send from outside an object. And overriding send requires some tricky code to account for the variable number of arguments that can be sent to any method.</p>
<p>That&#8217;s an exercise for another time.</p>
<p><strong>Suggestions/comments regarding the content of this series are welcome! Have your say!</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.khelll.com/blog/ruby/stackoverflow-cool-ruby-questions-2/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>StackOverflow cool Ruby questions</title>
		<link>http://www.khelll.com/blog/ruby/stackoverflow-cool-ruby-question/</link>
		<comments>http://www.khelll.com/blog/ruby/stackoverflow-cool-ruby-question/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 05:25:08 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Stackoverflow]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=573</guid>
		<description><![CDATA[I have participated heavily during the last 2 weeks in answering Ruby tagged questions on stackoverflow. That took place mainly after Ryan Bates tweet wishing to see more Ruby developers on stackoverflow. Since then I have enjoyed reading various kinds of questions that range in level from basic to professional ones and which cover various [...]]]></description>
			<content:encoded><![CDATA[<p>I have participated heavily during the last 2 weeks in answering <a href="http://stackoverflow.com/questions/tagged/ruby">Ruby tagged</a> questions on <a href="http://stackoverflow.com/">stackoverflow</a>. That took place mainly after Ryan Bates <a href="http://twitter.com/rbates/status/3270391247">tweet</a> wishing to see more Ruby developers on stackoverflow. Since then I have enjoyed reading various kinds of questions that range in level from basic to professional ones and which cover various stuff like normal questions, tricks, meta programming, best practices and language specific features.</p>
<p>So, I&#8217;m announcing in this post an <a href="http://www.khelll.com/blog/category/stackoverflow/">endless series</a> called &#8220;Stackoverflow cool Ruby questions&#8221; which will target cool Ruby questions on stackoverflow. I strongly recommend that you visit Stackoverflow on daily basis and try to participate if you have the time, but if you don&#8217;t, then I hope that you will enjoy this educational series.</p>
<p>There are currently more than 4,640 tagged Ruby questions, I&#8217;ll try to mix old + recent questions. I won&#8217;t cover basic questions here unless the question gets high votes. The covered questions will be related to new, tricky and controversial topics.</p>
<p>Please don&#8217;t hesitate to give any notes regarding the idea and the way the questions are picked and presented.</p>
<p>Let&#8217;s start this series, with 3 questions for this post:</p>
<h2>&#8216;Instance_eval&#8217; instead of &#8216;yield(self)&#8217;</h2>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/1485186/instance-eval-within-block">Instance Eval Within Block</a></p>
<p><strong>The question text is</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Builder
    <span style="color:#9966CC; font-weight:bold;">def</span> initialize
        <span style="color:#0066ff; font-weight:bold;">@lines</span> = <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#93;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
    <span style="color:#9966CC; font-weight:bold;">def</span> lines
        block_given? ? <span style="color:#9966CC; font-weight:bold;">yield</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF; font-weight:bold;">self</span><span style="color:#006600; font-weight:bold;">&#41;</span> : <span style="color:#0066ff; font-weight:bold;">@lines</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
    <span style="color:#9966CC; font-weight:bold;">def</span> add_line<span style="color:#006600; font-weight:bold;">&#40;</span> text <span style="color:#006600; font-weight:bold;">&#41;</span>
        <span style="color:#0066ff; font-weight:bold;">@lines</span> <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> text
    <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Now, how do I change this</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">my_builder = Builder.<span style="color:#9900CC;">new</span>
my_builder.<span style="color:#9900CC;">lines</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#006600; font-weight:bold;">|</span>b<span style="color:#006600; font-weight:bold;">|</span>
    b.<span style="color:#9900CC;">add_line</span> <span style="color:#996600;">&quot;foo&quot;</span>
    b.<span style="color:#9900CC;">add_line</span> <span style="color:#996600;">&quot;bar&quot;</span>
<span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#CC0066; font-weight:bold;">p</span> my_builder.<span style="color:#9900CC;">lines</span> <span style="color:#008000; font-style:italic;"># =&gt; [&quot;foo&quot;, &quot;bar&quot;]</span></pre></div></div>

<p>Into this?</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">my_builder = Builder.<span style="color:#9900CC;">new</span>
my_builder.<span style="color:#9900CC;">lines</span> <span style="color:#006600; font-weight:bold;">&#123;</span>
    add_line <span style="color:#996600;">&quot;foo&quot;</span>
    add_line <span style="color:#996600;">&quot;bar&quot;</span>
<span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#CC0066; font-weight:bold;">p</span> my_builder.<span style="color:#9900CC;">lines</span> <span style="color:#008000; font-style:italic;"># =&gt; [&quot;foo&quot;, &quot;bar&quot;]</span></pre></div></div>

<p><strong>The answer is</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Builder
    <span style="color:#9966CC; font-weight:bold;">def</span> initialize
        <span style="color:#0066ff; font-weight:bold;">@lines</span> = <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#93;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
    <span style="color:#9966CC; font-weight:bold;">def</span> lines<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&amp;</span>block<span style="color:#006600; font-weight:bold;">&#41;</span>
        block_given? ? instance_eval<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&amp;</span>block<span style="color:#006600; font-weight:bold;">&#41;</span> : <span style="color:#0066ff; font-weight:bold;">@lines</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
    <span style="color:#9966CC; font-weight:bold;">def</span> add_line<span style="color:#006600; font-weight:bold;">&#40;</span> text <span style="color:#006600; font-weight:bold;">&#41;</span>
        <span style="color:#0066ff; font-weight:bold;">@lines</span> <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> text
    <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
my_builder = Builder.<span style="color:#9900CC;">new</span>
my_builder.<span style="color:#9900CC;">lines</span> <span style="color:#006600; font-weight:bold;">&#123;</span>
    add_line <span style="color:#996600;">&quot;foo&quot;</span>
    add_line <span style="color:#996600;">&quot;bar&quot;</span>
<span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#CC0066; font-weight:bold;">p</span> my_builder.<span style="color:#9900CC;">lines</span> <span style="color:#008000; font-style:italic;"># =&gt; [&quot;foo&quot;, &quot;bar&quot;]</span></pre></div></div>

<p>The trick here is to use instance_eval which evaluates the passed block in the context of the current object called on.</p>
<h2>Determining whether a variable is any one of a list of values</h2>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/1487075/ruby-shortest-most-idiomatic-way-of-determining-whether-a-variable-is-any-one-of">Shortest/most idiomatic way of determining whether a variable is any one of a list of values</a></p>
<p><strong>The question text is:</strong></p>
<p>This seems a ridiculously simple question to be asking, but what&#8217;s the shortest/most idiomatic way of rewriting this in Ruby?</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">if</span> variable == <span style="color:#ff3333; font-weight:bold;">:a</span> <span style="color:#9966CC; font-weight:bold;">or</span> variable == <span style="color:#ff3333; font-weight:bold;">:b</span> <span style="color:#9966CC; font-weight:bold;">or</span> variable == <span style="color:#ff3333; font-weight:bold;">:c</span> <span style="color:#9966CC; font-weight:bold;">or</span> variable == <span style="color:#ff3333; font-weight:bold;">:d</span> <span style="color:#008000; font-style:italic;"># etc.</span></pre></div></div>

<p>I&#8217;ve previously seen this solution:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:a</span>, <span style="color:#ff3333; font-weight:bold;">:b</span>, <span style="color:#ff3333; font-weight:bold;">:c</span>, <span style="color:#ff3333; font-weight:bold;">:d</span><span style="color:#006600; font-weight:bold;">&#93;</span>.<span style="color:#9966CC; font-weight:bold;">include</span>? variable</pre></div></div>

<p>but this isn&#8217;t always functionally equivalent &#8211; I believe Array#include? actually looks to see if the variable object is contained in the list; it doesn&#8217;t take into account that the object may implement its own equality test with def ==(other).</p>
<p>Take, for example, Rails&#8217; <code>Mime::Type implementation: request.format == :html </code>may return true, but <code>[:html].include?(request.format)</code> will return false, as request.format is an instance of Mime::Type, not a symbol.</p>
<p><strong>The answer</strong>:<br />
Actually, #include? does use ==. The problem arises from the fact that if you do <code>[:a].include? foo</code>, it checks <code>:a == foo</code>, not <code>foo == :a</code>. <strong>That is, it uses the == method defined on the objects in the Array, not the variable. Therefore you can use it so long as you make sure the objects in the array have a proper == method.</strong></p>
<p>In cases where that won&#8217;t work, you can simplify your statement by removing the select statement and passing the block directly to any:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:a</span>, <span style="color:#ff3333; font-weight:bold;">:b</span>, <span style="color:#ff3333; font-weight:bold;">:c</span>, <span style="color:#ff3333; font-weight:bold;">:d</span><span style="color:#006600; font-weight:bold;">&#93;</span>.<span style="color:#9900CC;">any</span>? <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>f<span style="color:#006600; font-weight:bold;">|</span> variable == f<span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

<h2>Using &#8216;instance_eval&#8217; instead of &#8217;send&#8217;</h2>
<p><strong>The question title is</strong>: <a href="http://stackoverflow.com/questions/1485068/ruby-how-to-evalulate-multiple-methods-per-send-command">How to evaluate multiple methods per send command?</a></p>
<p><strong>The question text is</strong>:</p>
<p>Let&#8217;s say I have an XML::Element&#8230;I want to do something like:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">my_xml_element.<span style="color:#9900CC;">send</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;parent.next_sibling.next_sibling&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p><strong>The answer is:</strong></p>
<p>In your case it&#8217;s better to use instance_eval</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#996600;">&quot;Test&quot;</span>.<span style="color:#9900CC;">instance_eval</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#CC0066; font-weight:bold;">chop!</span>.<span style="color:#CC0066; font-weight:bold;">chop!</span><span style="color:#006600; font-weight:bold;">&#125;</span> <span style="color:#008000; font-style:italic;">#=&gt; &quot;Te&quot;</span></pre></div></div>

<p>And for your code:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">my_xml_element.<span style="color:#9900CC;">instance_eval</span><span style="color:#006600; font-weight:bold;">&#123;</span>parent.<span style="color:#9900CC;">next_sibling</span>.<span style="color:#9900CC;">next_sibling</span><span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.khelll.com/blog/ruby/stackoverflow-cool-ruby-question/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Bringing web applications to your Desktop with Prism</title>
		<link>http://www.khelll.com/blog/web/bringing-web-applications-to-your-desktop-with-prism/</link>
		<comments>http://www.khelll.com/blog/web/bringing-web-applications-to-your-desktop-with-prism/#comments</comments>
		<pubDate>Sun, 23 Aug 2009 05:48:51 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[Web]]></category>
		<category><![CDATA[Desktop Application]]></category>
		<category><![CDATA[Prism]]></category>
		<category><![CDATA[Web Application]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=558</guid>
		<description><![CDATA[I have almost finished working on a web app that will be used inside intranets by students willing to do their English language exams interactively. I have reached the point where I want the app to have as much as possible the look of a desktop one. So I started thinking that may be with [...]]]></description>
			<content:encoded><![CDATA[<p>I have almost finished working on a web app that will be used inside intranets by students willing to do their English language exams interactively. I have reached the point where I want the app to have as much as possible the look of a desktop one. So I started thinking that may be with the help of Javascript I might be able to remove the browser toolbar; not a bad idea so far. Also I wanted to disable both back and refresh buttons because the exam is timed and the student will have a time counter for each section. However after I ran through<a href="http://stackoverflow.com/questions/961188/disable-browsers-back-button"> this</a> thread and found a strong resistance towards such ideas, I decided to go with other solution. Simply I chose to remove the toolbar and use keystroke events to determine which ones are related to navigation, just like &#8216;f5&#8242; and &#8216;backspace&#8217;. So far so good, but after few minutes of work on this approach, I had few thoughts at mind: &#8220;Why am I doing so? Do I really need a browser to do this? shouldn&#8217;t be there any software that can render HTML markup and can have a customized interface?&#8221;<br />
I start searching for such a software and found <a href="http://prism.mozilla.com/">Prism</a>, which is a cool product by Mozilla that helps you turning a web app into a desktop like one. Taken from the product <a href="http://prism.mozilla.com/why/">why</a> page:</p>
<blockquote><p>Instead of running all your web apps in the browser, Prism lets you run them in their own window just like normal applications. A single faulty app or web page can no longer take down everything you are working on. </p></blockquote>
<p>Prism is so easy to be used, it takes 1 minute approximately to turn your web app into a desktop one and you will gain many Desktop integration things like:</p>
<ul>
<li>Access web apps from system taskbar or dock</li>
<li>Tray icon and dock menus</li>
<li>Associate applications with browser links</li>
<li>Minimize to tray</li>
<li>System tray icon and dock badges</li>
</ul>
<p>Prism can be used as a stand alone soft, or just another Firefox addon(this one didn&#8217;t play well with me). Give it a shoot, you won&#8217;t regret it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.khelll.com/blog/web/bringing-web-applications-to-your-desktop-with-prism/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Observer and Singleton design patterns in Ruby</title>
		<link>http://www.khelll.com/blog/ruby/observer-and-singleton-design-patterns-in-ruby/</link>
		<comments>http://www.khelll.com/blog/ruby/observer-and-singleton-design-patterns-in-ruby/#comments</comments>
		<pubDate>Fri, 21 Aug 2009 14:36:05 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Observer]]></category>
		<category><![CDATA[Singleton]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=551</guid>
		<description><![CDATA[This is my first article in http://railsmagazine.com, it was published in issue 3, so basically I&#8217;m just republishing it here again.
Observer and singleton are two common design patterns that a programmer should be familiar with, however what made me write about them, is that both are there out of the box for you to use [...]]]></description>
			<content:encoded><![CDATA[<p><em>This is my first article in <a href="http://www.railsmagazine.com/">http://railsmagazine.com</a>, it was published in <a href="http://railsmagazine.com/issues/3">issue 3</a>, so basically I&#8217;m just republishing it here again.</em></p>
<p>Observer and singleton are two common design patterns that a programmer should be familiar with, however what made me write about them, is that both are there out of the box for you to use in ruby.<br />
So let’s have a look at both and see how ruby help you use them directly:</p>
<h2>Observer Design Pattern</h2>
<p>According to Wikipedia:</p>
<blockquote><p>The observer pattern (sometimes known as publish/subscribe) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.</p></blockquote>
<p>So how does ruby help you implementing this design pattern? Well, the answer is by mixing the observable module into your subject (observed object).<br />
Let’s take an example, let’s suppose we have a banking mechanism that notifies the user by several ways upon withdrawal operations that leaves the account with balance less or equal to $0.5.<br />
If we look deeply at this problem, we can qualify it as a good candidate for observer design pattern, where the bank account is our subject and the notification system as the observer.<br />
Here is a code snippet for this problem and it’s solution:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># require the observer lib file</span>
<span style="color:#CC0066; font-weight:bold;">require</span> “observer”
<span style="color:#9966CC; font-weight:bold;">class</span> Notifier
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> EmailNotifier <span style="color:#006600; font-weight:bold;">&lt;</span> Notifier
  <span style="color:#9966CC; font-weight:bold;">def</span> update<span style="color:#006600; font-weight:bold;">&#40;</span>bank_account<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> bank_account.<span style="color:#9900CC;">balance</span> <span style="color:#006600; font-weight:bold;">&lt;</span>= <span style="color:#006666;">10</span>
      <span style="color:#CC0066; font-weight:bold;">puts</span> “Sending email to: ‘<span style="color:#008000; font-style:italic;">#{bank_account.owner}’ informing him with his account balance: #{bank_account.balance}$.”</span>
      <span style="color:#008000; font-style:italic;"># send the email mechanism</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> SMSNotifier <span style="color:#006600; font-weight:bold;">&lt;</span> Notifier
  <span style="color:#9966CC; font-weight:bold;">def</span> update<span style="color:#006600; font-weight:bold;">&#40;</span>bank_account<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> bank_account.<span style="color:#9900CC;">balance</span> <span style="color:#006600; font-weight:bold;">&lt;</span>= <span style="color:#006666;">0.5</span> 
      <span style="color:#CC0066; font-weight:bold;">puts</span> “Sending SMS to: ‘<span style="color:#008000; font-style:italic;">#{bank_account.owner}’ informing him with his account balance: #{bank_account.balance}$.”</span>
      <span style="color:#008000; font-style:italic;"># send sms mechanism</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> BankAccount
  <span style="color:#008000; font-style:italic;"># include the observable module</span>
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#CC00FF; font-weight:bold;">Observable</span> 
  attr_reader <span style="color:#ff3333; font-weight:bold;">:owner</span>,:balance
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize<span style="color:#006600; font-weight:bold;">&#40;</span>owner,amount<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0066ff; font-weight:bold;">@owner</span>,@balance = owner,amount
    <span style="color:#008000; font-style:italic;"># adding list of observes to the account</span>
    add_observer EmailNotifier.<span style="color:#9900CC;">new</span>  
    add_observer SMSNotifier.<span style="color:#9900CC;">new</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># withdraw operation</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> withdraw<span style="color:#006600; font-weight:bold;">&#40;</span>amount<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#008000; font-style:italic;"># do whatever you need</span>
    <span style="color:#0066ff; font-weight:bold;">@balance</span> <span style="color:#006600; font-weight:bold;">-</span>=amount <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#006600; font-weight:bold;">&#40;</span>@balance <span style="color:#006600; font-weight:bold;">-</span> amount<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&gt;</span> <span style="color:#006666;">0</span>
    <span style="color:#008000; font-style:italic;"># now here comes our logic</span>
    <span style="color:#008000; font-style:italic;"># issue that the account has changed</span>
    changed
    <span style="color:#008000; font-style:italic;"># notify the observers</span>
    notify_observers <span style="color:#0000FF; font-weight:bold;">self</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
account = BankAccount.<span style="color:#9900CC;">new</span> “Jim Oslen”, <span style="color:#006666;">100</span>
account.<span style="color:#9900CC;">withdraw</span> <span style="color:#006666;">99.5</span>
<span style="color:#008000; font-style:italic;">#=&gt;Sending email to: ‘Jim Oslen’ informing him with his account balance: 0.5$.</span>
<span style="color:#008000; font-style:italic;">#=&gt;Sending SMS to: ‘Jim Oslen’ informing him with his account balance: 0.5$.</span></pre></div></div>

<p>So to user ruby observer lib we have to implement four things:<br />
1- Require the ‘observer’ lib and include it inside the subject (observed) class.<br />
2- Declare the object to be ‘changed’ and then notify the observers when needed – just like we did in ‘withdraw’ method.<br />
3- Declare all needed observers objects that will observe the subject.<br />
4- Each observer must implement an ‘update’ method that  will be called by the subject.</p>
<h2>Observers in Rails</h2>
<p>You can find observers in rails when using ActiveRecord, it’s a way to take out all <a href="http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html">ActiveRecord callbacks</a> out of the model, for example a one would do this:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> User <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
  after_create <span style="color:#ff3333; font-weight:bold;">:send_email</span>
  private
  <span style="color:#9966CC; font-weight:bold;">def</span> send_email
    <span style="color:#008000; font-style:italic;">#send a welcome email</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>A neater solution is to use Observers:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> UserObserver <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Observer</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> after_create<span style="color:#006600; font-weight:bold;">&#40;</span>user<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#008000; font-style:italic;">#send a welcome email</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>You can generate the previous observer using the following command:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">ruby script<span style="color: #000000; font-weight: bold;">/</span>generate observer User</pre></div></div>

<p>You still can have observers that map to models that don’t match with the observer name using the ‘observe’ class method, you also can observe multiple models using the same method:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> NotificationObserver <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Observer</span>
  observe <span style="color:#ff3333; font-weight:bold;">:user</span>, <span style="color:#ff3333; font-weight:bold;">:post</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> after_create<span style="color:#006600; font-weight:bold;">&#40;</span>record<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#008000; font-style:italic;">#send thanks email</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Finally don’t forget to add the following line inside config/environment.rb to define observers:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">config.<span style="color:#9900CC;">active_record</span>.<span style="color:#9900CC;">observers</span> = <span style="color:#ff3333; font-weight:bold;">:user_observer</span></pre></div></div>

<h2>Singleton Design Pattern</h2>
<p>According to Wikipedia:</p>
<blockquote><p>In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. (This concept is also sometimes generalized to restrict the instance to a specific number of objects – for example, we can restrict the number of instances to five objects.) This is useful when exactly one object is needed to coordinate actions across the system.</p></blockquote>
<p>The singleton design pattern is used to have one instance of some class, typically there are many places where you might want to do so, just like having one database connection, one LDAP connection, one logger instance or even one configuration object for your application.<br />
In ruby you can use the singleton module to have the job done for you, let’s take ‘application configuration’ as an example and check how we can use ruby to do the job:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># require singleton lib</span>
<span style="color:#CC0066; font-weight:bold;">require</span> ‘singleton’
<span style="color:#9966CC; font-weight:bold;">class</span> AppConfig
  <span style="color:#008000; font-style:italic;"># mixin the singleton module</span>
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#CC00FF; font-weight:bold;">Singleton</span>
  <span style="color:#008000; font-style:italic;"># do the actual app configuration</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> load_config<span style="color:#006600; font-weight:bold;">&#40;</span>file<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#008000; font-style:italic;"># do your work here</span>
    <span style="color:#CC0066; font-weight:bold;">puts</span> “Application configuration file was loaded from file: <span style="color:#008000; font-style:italic;">#{file}”</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
conf1 = AppConfig.<span style="color:#9900CC;">instance</span>
conf1.<span style="color:#9900CC;">load_config</span> “<span style="color:#006600; font-weight:bold;">/</span>home<span style="color:#006600; font-weight:bold;">/</span>khelll<span style="color:#006600; font-weight:bold;">/</span>conf.<span style="color:#9900CC;">yml</span>”
<span style="color:#008000; font-style:italic;">#=&gt;Application configuration file was loaded from file: /home/khelll/conf.yml</span>
conf2 = AppConfig.<span style="color:#9900CC;">instance</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> conf1 == conf2
<span style="color:#008000; font-style:italic;">#=&gt;true</span>
<span style="color:#008000; font-style:italic;"># notice the following 2 lines won’t work</span>
<span style="color:#008000; font-style:italic;"># new method is private</span>
AppConfig.<span style="color:#9900CC;">new</span> <span style="color:#9966CC; font-weight:bold;">rescue</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">puts</span> $!<span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#008000; font-style:italic;">#=&gt;private method `new’ called for AppConfig:Class</span>
<span style="color:#008000; font-style:italic;"># dup won’t work</span>
conf1.<span style="color:#9900CC;">dup</span> <span style="color:#9966CC; font-weight:bold;">rescue</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">puts</span> $!<span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#008000; font-style:italic;">#=&gt;can’t dup instance of singleton AppConfig</span></pre></div></div>

<p>So what does ruby do when you include the singleton method inside your class?<br />
1- It makes the ‘new’ method private and so you can’t use it.<br />
2- It adds a class method called instance that instantiates only one instance of the class.<br />
So to use ruby singleton module you need two things:<br />
1- Require the lib ‘singleton’ then include it inside the desired<br />
class.<br />
2- Use the ‘instance’ method to get the instance you need.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.khelll.com/blog/ruby/observer-and-singleton-design-patterns-in-ruby/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Ruby 1.9 Encoding Fun</title>
		<link>http://www.khelll.com/blog/ruby/ruby-1-9-encoding-fun/</link>
		<comments>http://www.khelll.com/blog/ruby/ruby-1-9-encoding-fun/#comments</comments>
		<pubDate>Mon, 13 Jul 2009 13:52:23 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Encoding]]></category>
		<category><![CDATA[fun]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=517</guid>
		<description><![CDATA[Ruby 1.9 has a great support for encoding, this post covers that for a big deal, however with this support out of the box, things like this becomes easier, just note the source code is not limited to few types of encoding just like Ruby 1.8.

# coding: UTF-8
&#160;
π = Math::PI
&#160;
def √&#40;x&#41; 
  Math.sqrt&#40;x&#41;
end
&#160;
def ∑&#40;r&#41;
 [...]]]></description>
			<content:encoded><![CDATA[<p>Ruby 1.9 has a great support for encoding, <a href="http://blog.nuclearsquid.com/writings/ruby-1-9-encodings">this</a> post covers that for a big deal, however with this support out of the box, things like <a href="http://www.oreillynet.com/ruby/blog/2007/10/fun_with_unicode_1.html">this</a> becomes easier, just note the source code is not limited to few types of encoding just like Ruby 1.8.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># coding: UTF-8</span>
&nbsp;
π = <span style="color:#6666ff; font-weight:bold;">Math::PI</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> √<span style="color:#006600; font-weight:bold;">&#40;</span>x<span style="color:#006600; font-weight:bold;">&#41;</span> 
  <span style="color:#CC00FF; font-weight:bold;">Math</span>.<span style="color:#9900CC;">sqrt</span><span style="color:#006600; font-weight:bold;">&#40;</span>x<span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> ∑<span style="color:#006600; font-weight:bold;">&#40;</span>r<span style="color:#006600; font-weight:bold;">&#41;</span>
  r.<span style="color:#9900CC;">inject</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>sum,val<span style="color:#006600; font-weight:bold;">|</span> sum <span style="color:#006600; font-weight:bold;">+</span> <span style="color:#006600; font-weight:bold;">&#40;</span>block_given? ? <span style="color:#9966CC; font-weight:bold;">yield</span><span style="color:#006600; font-weight:bold;">&#40;</span>val<span style="color:#006600; font-weight:bold;">&#41;</span> : val<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#9966CC; font-weight:bold;">end</span> 
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> ∏<span style="color:#006600; font-weight:bold;">&#40;</span>r<span style="color:#006600; font-weight:bold;">&#41;</span>
  r.<span style="color:#9900CC;">inject</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>mul,val<span style="color:#006600; font-weight:bold;">|</span> mul <span style="color:#006600; font-weight:bold;">*</span> <span style="color:#006600; font-weight:bold;">&#40;</span>block_given? ? <span style="color:#9966CC; font-weight:bold;">yield</span><span style="color:#006600; font-weight:bold;">&#40;</span>val<span style="color:#006600; font-weight:bold;">&#41;</span> : val<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#9966CC; font-weight:bold;">end</span> 
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> ¬<span style="color:#006600; font-weight:bold;">&#40;</span>x<span style="color:#006600; font-weight:bold;">&#41;</span>
  !x
<span style="color:#9966CC; font-weight:bold;">end</span>	
&nbsp;
<span style="color:#CC0066; font-weight:bold;">p</span> π <span style="color:#008000; font-style:italic;">#=&gt; 3.14159265358979</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">p</span> √<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">9</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 3.0</span>
&nbsp;
range = 1..6 
&nbsp;
<span style="color:#CC0066; font-weight:bold;">p</span> ∑<span style="color:#006600; font-weight:bold;">&#40;</span>range<span style="color:#006600; font-weight:bold;">&#41;</span>  <span style="color:#008000; font-style:italic;">#=&gt; 21</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">p</span> ∑<span style="color:#006600; font-weight:bold;">&#40;</span>range<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> x<span style="color:#006600; font-weight:bold;">**</span><span style="color:#006666;">2</span><span style="color:#006600; font-weight:bold;">&#125;</span>  <span style="color:#008000; font-style:italic;">#=&gt; 91</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">p</span> ∏<span style="color:#006600; font-weight:bold;">&#40;</span>range<span style="color:#006600; font-weight:bold;">&#41;</span>  <span style="color:#008000; font-style:italic;">#=&gt; 720</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">p</span> ∏<span style="color:#006600; font-weight:bold;">&#40;</span>range<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> x<span style="color:#006600; font-weight:bold;">**</span><span style="color:#006666;">2</span><span style="color:#006600; font-weight:bold;">&#125;</span>  <span style="color:#008000; font-style:italic;">#=&gt; 518400</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">p</span> ¬<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&gt;</span><span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; false</span></pre></div></div>

<p><strong>Please note that previous example could work also with Ruby 1.8 using the flag<code> -Ku</code>, I just wanted to explain the idea of using different types of encoding in Ruby 1.9.</strong></p>
<p>So all you need to do is to set whatever encoding you want for your source code at the very beginning of the file:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># coding: UTF-8</span></pre></div></div>

<p>Many other things can be done, just give yourself a moment and think what you can do!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.khelll.com/blog/ruby/ruby-1-9-encoding-fun/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Scala is my next choice</title>
		<link>http://www.khelll.com/blog/scala/scala-is-my-next-choice/</link>
		<comments>http://www.khelll.com/blog/scala/scala-is-my-next-choice/#comments</comments>
		<pubDate>Sun, 12 Jul 2009 11:39:45 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[Functional Programming]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=435</guid>
		<description><![CDATA[I have done Pascal, C, C++, Java, PHP, Ruby, Groovy and recently Scala, which I found it to be a unique language compared to anything else I have ever worked with. My journey with this language started after the Twitter&#8217;s Ruby vs Scala debate. Now and after few months of work with this language I [...]]]></description>
			<content:encoded><![CDATA[<p>I have done Pascal, C, C++, Java, PHP, Ruby, Groovy and recently Scala, which I found it to be a unique language compared to anything else I have ever worked with. My journey with this language started after the Twitter&#8217;s Ruby vs Scala <a href="http://topsecretproject.finitestatemachine.com/2009/04/the-great-twitter-ruby-vs-scala-war-debate/">debate</a>. Now and after few months of work with this language I really want to share you two ideas that are no secrets anymore:</p>
<ul>
<li>Scala Does Rock.</li>
<li>I do believe this language should be taught in CS colleges and institutes.</li>
</ul>
<p>I&#8217;m going to justify my opinion during this article, just before doing so I have few notes I feel like I have to address:</p>
<ul>
<li>This article is not to compare languages, it&#8217;s to address why you should learn Scala.</li>
<li>Scala has 2 implementations right now, one that runs on the <a href="http://en.wikipedia.org/wiki/Java_Virtual_Machine">JVM</a>, and one that runs on the <a href="http://en.wikipedia.org/wiki/Common_Language_Runtime">CLR</a>. However the JVM one  is more mature, and I believe it&#8217;s better to stick to the <a href="http://www.infoq.com/interviews/Lift-Scala-David-Pollak">advice</a> of David Pollack(Lift framework creator) to use <code>F#</code> if you want to work with <code>.Net</code> framework. However I will stick to JVM implementation in this article.</li>
<li>I&#8217;m a Rubiest, and I still like Ruby cause it&#8217;s the best dynamic language ever, but I like Scala also because it has some features that are so powerful for other work domains.</li>
</ul>
<p>Now, let&#8217;s dive into the some reasons that&#8217;s makes Scala my next language of choice:</p>
<h2>A hyper language</h2>
<p>Scala is a hyper language that enables you to code in <a href="http://en.wikipedia.org/wiki/Imperative_programming">imperative</a> and <a href="http://en.wikipedia.org/wiki/Functional_programming">functional</a> paradigms, so you can code with the normal imperative style just like we do in C, Java, PHP and many other languages, or you can code in a functional style like we do in Lisp for example, or you can mix both, just like we do in Ruby or Groovy.</p>
<p>However, one distinct to Ruby and Groovy when talking about the functional paradigm, is that Scala almost supports all known features of functional languages, like Pattern matching, Lazy initialization, Partial Functions, Immutability, etc&#8230;  </p>
<p>That&#8217;s said, it&#8217;s important to address the fact that the power of Scala comes from it&#8217;s support for the functional paradigm, which makes the language a high-level one. A high-level language makes you focus on &#8216;what&#8217; to do rather than &#8216;how&#8217; to do.</p>
<p>Look at this Java example:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> x <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">2</span>,<span style="color: #cc66cc;">3</span>,<span style="color: #cc66cc;">4</span>,<span style="color: #cc66cc;">5</span>,<span style="color: #cc66cc;">6</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
ArrayList<span style="color: #339933;">&lt;</span>Integer<span style="color: #339933;">&gt;</span> res <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>Integer<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> v <span style="color: #339933;">:</span> x<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>v <span style="color: #339933;">%</span> <span style="color: #cc66cc;">2</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> res.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Integer</span><span style="color: #009900;">&#40;</span>v<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>If you focus on the previous example, you will notice that the &#8216;what&#8217; part of what I want to do (Filtering odd values) comes on the 4th line, and the other lines are just the &#8216;how&#8217; part of it(result var initialization and a loop), thus if I want to write another filter for even numbers, It will take me another 5 lines to do the same, while in a high-level languages like Scala, you will need to express the &#8216;what&#8217; part only:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">val</span> x <span style="color: #000080;">=</span> Array<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span>,<span style="color: #F78811;">2</span>,<span style="color: #F78811;">3</span>,<span style="color: #F78811;">4</span>,<span style="color: #F78811;">5</span>,<span style="color: #F78811;">6</span><span style="color: #F78811;">&#41;</span>
<span style="color: #0000ff; font-weight: bold;">val</span> res <span style="color: #000080;">=</span> x filter <span style="color: #F78811;">&#40;</span> <span style="color: #000080;">_</span> <span style="color: #000080;">%</span> <span style="color: #F78811;">2</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">1</span> <span style="color: #F78811;">&#41;</span> <span style="color: #008000; font-style: italic;">//filtering odd numbers</span>
<span style="color: #0000ff; font-weight: bold;">val</span> res2 <span style="color: #000080;">=</span> x filter <span style="color: #F78811;">&#40;</span> <span style="color: #000080;">_</span> <span style="color: #000080;">%</span> <span style="color: #F78811;">2</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">0</span> <span style="color: #F78811;">&#41;</span> <span style="color: #008000; font-style: italic;">//filtering even numbers</span></pre></div></div>

<p>Notice how the previous code snippet is more readable and more concise than the Java equivalent.</p>
<h2>Efficient</h2>
<p>Scala is an efficient language, actually due to the <a href="http://stronglytypedblog.blogspot.com/2009/07/java-vs-Scala-vs-groovy-performance.html">latest benchmarks</a> Scala is almost as fast as Java. The JVM implementation of Scala compiles down to <a href="http://en.wikipedia.org/wiki/Bytecode">bytecode</a>, but during so, the code passes through optimization phaze. An optimization example is the <a href="http://en.wikipedia.org/wiki/Tail_recursion">tail recursion optimization</a>, to help you stick to the functional paradigm without sacrificing the performance. Another example is the optimization done to convert Scala value type objects to Java primitive types. </p>
<h2> Scalable </h2>
<p>The name of Scala language comes form the word &#8216;Scalable&#8217;, meaning that this language grows with the demand of its users. <strong>So basically you can add new type and control structures</strong>. For example I want to add a simple &#8216;loop&#8217; control structure:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #008000; font-style: italic;">// simple implementation</span>
<span style="color: #0000ff; font-weight: bold;">def</span> loop<span style="color: #F78811;">&#40;</span>range<span style="color: #000080;">:</span> Range<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span>op<span style="color: #000080;">:</span> Int<span style="color: #000080;">=&gt;</span> Unit<span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span>
     range foreach <span style="color: #F78811;">&#40;</span>op<span style="color: #F78811;">&#41;</span>                       
<span style="color: #F78811;">&#125;</span>
&nbsp;
loop<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span> to <span style="color: #F78811;">5</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#123;</span>println<span style="color: #F78811;">&#125;</span> <span style="color: #008000; font-style: italic;">// 1 2 3 4 5</span>
loop<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span> to <span style="color: #F78811;">5</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#123;</span>x <span style="color: #000080;">=&gt;</span> <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>x <span style="color: #000080;">%</span> <span style="color: #F78811;">2</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span> println<span style="color: #F78811;">&#40;</span>x<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#125;</span> <span style="color: #008000; font-style: italic;">// 2 4</span></pre></div></div>

<p>A more comprehensive example is the <a href="http://www.Scala-lang.org/docu/files/api/Scala/actors/Actor.html">Actor lib</a>, which is added as an extension to the language, we will talk about it later on.</p>
<p>However what makes Scala Scalable is two related things: being pure object oriented and being functional.</p>
<h3>Object Oriented</h3>
<ul>
<li>Everything in Scala is an object(except for the objects&#8217; methods), so there is no need to differentiate between primitive or reference types, this is called: <strong>Uniform Object Model</strong>. But as I mentioned earlier during the optimization process, value type objects are converted to Java primitive types, so don&#8217;t be worried about the performance.<br />
There are also singleton objects to group class methods inside them.</li>
<li>All operations are method calls, <code>+ - * ! /</code> all are methods, so there no need for operator overloading.   </li>
<li>A great fine-grained access control, where you can control access for certain methods for certain packages also.</li>
<li>Scala has <code>traits</code>, similar to <code>mixins</code> in Ruby, which are like <code>interfaces</code> in Java but have some of their methods implemented, thus you can have rich wrappers and interfaces out of the box.</li>
</ul>
<h3>Functional</h3>
<p>A functional language has many characteristics, however what we care for in our Scalability context is 2 facts:</p>
<h4>Functions are first-class values</h4>
<p>Which means that you can pass them as values and return them as values as well. This leads to concise readable code just like the filtering examples mentioned above.</p>
<h4>Pure functions</h4>
<p>Scala encourages pure functions that have no side effects, meaning: when you have the same input, you will always have the same output. This will result in safer and easier to test code.<br />
But how does Scala encourages pure functions? By <strong>immutability</strong>: Favoring fixed references(like final in java or constants in other languages) and having immutable data structures that once created can&#8217;t be modified. </p>
<p>Immutability is the safe guard to have pure functions, but it&#8217;s not the only way. You still can write safe code without immutability. That&#8217;s why Scala doesn&#8217;t force immutability but it encourages it. Eventually you will find that many data structures in Scala have 2 implementations, one is mutable and the other is immutable, immutable data structures are imported by default.</p>
<p>Some concerns regarding performance might arise when talking about immutability, and while these concerns are valid in this context, it turned out that things are somehow reversed when it comes to Scala. Immutable data structures tend to be more efficient than mutable ones. One reason for that is the existence of a robust garbage collector like the one of JVM. You can find more information about the efficiency of immutable data structures in Scala in this <a href="http://www.codecommit.com/blog/Scala/Scala-collections-for-the-easily-bored-part-1">blog post</a>.</p>
<h2>Better concurrency model</h2>
<p>When it comes to threading, Scala supports the traditional <code>shared data</code> model. However and after long experiments with this model, many people found it to be so hard to to implement and test concurrent code written using this model. You will always have to consider deadlocks and race conditions. Thus Scala suggests another concurrency model called <a href = "http://www.Scala-lang.org/node/242">Actors</a>, where an actor <strong>sends and receives asynchronous messages in it&#8217;s inbox instead of sharing data</strong>. This is called: <code>shared nothing</code> model. Once you stop thinking about shared data, you relief yourself from the headache of thinking of code synchronization and deadlocks problems. </p>
<p>Together the immutability nature of the sent messages and the serial processing of messages in the actor, leads to easier concurrency support.<br />
There are 2 articles(<a href="http://www.ibm.com/developerworks/java/library/j-Scala02049.html?S_TACT=105AGX02&#038;S_CMP=EDU">1</a>,<a href="http://www.ibm.com/developerworks/java/library/j-Scala04109.html?S_TACT=105AGX02&#038;S_CMP=EDU">2</a>) on the IBM developerWorks website that cover Scala concurrency deeply. Please refer back to them to have a better idea about this topic.</p>
<p>Before I move to the next point I need to mention the fact that some people consider the use of <code>Actors</code> as an evolutionary progress in programming languages. As Java came and relieved programmers from the headache of pointers and memory management, Scala came to relief programmers from thinking all the time of code synchronization and the problems raised by shared data model.</p>
<h2>Statically typed</h2>
<p>When i wanted to cover this point, I found myself trying to weigh both the pros and cons of a statically typed language. Actually there is an endless debate regarding this topic but I tried to sum things up to two points that I found most people talking about:</p>
<h3>Code written in statically typed languages is more robust</h3>
<p>It&#8217;s true that with the existence of TDD most of the talk about dynamically typed systems and robust code starts to lose its value, but one fact still exists: in dynamically typed languages you write more tests to check types, while in statically typed ones, you leave things out for the compiler. Also some people argue that with a statically typed language you have a better self documenting code.</p>
<h3>Code written in statically typed languages is so strict and verbose</h3>
<p>Fans(just like me) of dynamically typed languages argue that they can produce more dynamic code structures through duck typing. Also they complain about the verbosity introduced with statically typed languages.
 </ol>
<p>You can read more about static versus dynamic typing <a href="http://www.pathf.com/blogs/2009/04/static-typing-and-the-paranoid-style-of-programming/">here</a>. </p>
<p>Scala as a statically typed language will gain the first point, but how about the second one?<br />
Scala has a<strong> flexible</strong> type system, and may be the best of it&#8217;s type. So in many cases this system will be able to infer the type in case you didn&#8217;t specify it.<br />
For example you can do this:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">val</span> list<span style="color: #000080;">:</span> List<span style="color: #F78811;">&#91;</span>String<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> List<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;one&quot;</span>, <span style="color: #6666FF;">&quot;two&quot;</span>, <span style="color: #6666FF;">&quot;three&quot;</span><span style="color: #F78811;">&#41;</span>
<span style="color: #008000; font-style: italic;">//list: List[String] = List(one, two, three)</span>
&nbsp;
<span style="color: #0000ff; font-weight: bold;">val</span> s<span style="color: #000080;">:</span> String <span style="color: #000080;">=</span> <span style="color: #6666FF;">&quot;Hello World!&quot;</span>
<span style="color: #008000; font-style: italic;">//s: java.lang.String = hello world!</span></pre></div></div>

<p>But you can do this also:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">val</span> list <span style="color: #000080;">=</span> List<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;one&quot;</span>, <span style="color: #6666FF;">&quot;two&quot;</span>, <span style="color: #6666FF;">&quot;three&quot;</span><span style="color: #F78811;">&#41;</span>
<span style="color: #008000; font-style: italic;">//list: List[String] = List(one, two, three)</span>
&nbsp;
<span style="color: #0000ff; font-weight: bold;">val</span> s <span style="color: #000080;">=</span> <span style="color: #6666FF;">&quot;Hello World!&quot;</span>
<span style="color: #008000; font-style: italic;">//s: java.lang.String = hello world!</span></pre></div></div>

<p>Well, that&#8217;s cool as it solves the verbosity problem somehow. But what about things like duck typing?<br />
Again: Scala&#8217;s type system has some flexibility that enables you to do things like:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> eat<span style="color: #F78811;">&#91;</span>T <span style="color: #000080;">&lt;:</span> Animal<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>a<span style="color: #000080;">:</span> T<span style="color: #F78811;">&#41;</span> <span style="color: #008000; font-style: italic;">// whatever</span></pre></div></div>

<p>Where we define the Type <code>T</code> to be a sub type of <code>Animal</code>. It can be more flexible even:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> eat<span style="color: #F78811;">&#91;</span>T <span style="color: #000080;">&lt;:</span> <span style="color: #F78811;">&#123;</span><span style="color: #0000ff; font-weight: bold;">def</span> eat<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> Unit<span style="color: #F78811;">&#125;</span><span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>a<span style="color: #000080;">:</span> T<span style="color: #F78811;">&#41;</span> <span style="color: #008000; font-style: italic;">// whatever</span></pre></div></div>

<p>Where we define the type <code>T</code> to be a type that has the method <code>eat.</code><br />
Actually Scala&#8217;s type system is so rich, you can find more about that <a href="http://www.artima.com/Scalazine/articles/Scalas_type_system.html">here</a>.</p>
<h2>Pattern matching</h2>
<p>I have to admit that I hesitated a lot to write about this feature, actually I didn&#8217;t want to cover functional features of Scala, but after I read <a href="http://blog.rubybestpractices.com/posts/gregory/008-decorator-delegator-disco.html">this</a> specific post regarding <code>switch</code> use with objects, I thought it&#8217;s good to talk about this feature.<br />
So basically and taken from this <a href="http://www.artima.com/scalazine/articles/pattern_matching.html">post </a>:</p>
<blockquote><p>
So what does pattern matching do? It lets you match a value against several cases, sort of like a switch statement in Java. But instead of just matching numbers, which is what switch statements do, you match what are essentially the creation forms of objects. </p></blockquote>
<p>And the following example:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;">x <span style="color: #0000ff; font-weight: bold;">match</span> <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">case</span> Address<span style="color: #F78811;">&#40;</span>Name<span style="color: #F78811;">&#40;</span>first, last<span style="color: #F78811;">&#41;</span>, street, city, state, zip<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> println<span style="color: #F78811;">&#40;</span>last + <span style="color: #6666FF;">&quot;, &quot;</span> + zip<span style="color: #F78811;">&#41;</span>
  <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #000080;">_</span> <span style="color: #000080;">=&gt;</span> println<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;not an address&quot;</span><span style="color: #F78811;">&#41;</span> <span style="color: #008000; font-style: italic;">// the default case</span>
<span style="color: #F78811;">&#125;</span></pre></div></div>

<p>In the first case, the pattern Name(first, last) is nested inside the pattern Address(&#8230;). The last value, which was passed to the Name constructor, is &#8220;extracted&#8221; and therefore usable in the expression to the right of the arrow. </p>
<p>Then </p>
<blockquote><p><strong>The purpose of pattern matching</strong></p>
<p>So why do you need pattern matching? We all have complicated data. If we adhere to a strict object-oriented style, then we don&#8217;t want to look inside these trees of data. Instead, we want to call methods, and let the methods do the right thing. If we have the ability to do that, we don&#8217;t need pattern matching so much, because the methods do what we need. But there are many situations where the objects don&#8217;t have the methods we need, and we can&#8217;t (or don&#8217;t want to) add new methods to the objects. </p></blockquote>
<p>So, Pattern matching is considered a valid way of extensibility, and it offers a great solution to this problem apart from the verbosity that comes with <a href="http://en.wikipedia.org/wiki/Visitor_pattern">Visitor design pattern</a>.</p>
<p>Anyway, it&#8217;s highly recommended that you read the &#8220;<em>Two directions of extensibility</em>&#8221; in the previous mentioned article.</p>
<h2>Easy DSLs</h2>
<p>Scala is very good for coding <a href="http://en.wikipedia.org/wiki/Domain-specific_language">DSLs</a>. Actually Scala is suitable for both Internal and external DSLs. You can find in this <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=251945">article</a> a little comparison of features between Ruby and Scala for writing internal DSLs. Check this cool post on internal DSLs using Scala: <a href=" http://gabrielsw.blogspot.com/2009/06/boolean-algebra-internal-dsl-in-scala.html">Boolean Algebra Internal DSL in Scala (aka fun with Unicode names )</a>.<br />
Also when it comes to External DSLs, Scala should be your first choice, and the reason behind that is the <a href="http://www.Scala-lang.org/docu/files/api/Scala/util/parsing/combinator/Parsers.html">parser combinator</a> lib, that makes writing compilers for new languages is really cool. You&#8217;d better follow this cool <a href="http://www.codecommit.com/blog/Scala/the-magic-behind-parser-combinators">post</a> to get a better idea about what Scala can do.</p>
<h2>Interoperable with Java code</h2>
<p>The JVM implementation of Scala have seamless integration with Java platform, actually many Scala types compiles down to Java types, so you can use Java libs safely. Also you can make some work between JVM languages like <a href="http://www.jRuby.org">JRuby</a>, <a href="http://groovy.codehaus.org/"> Groovy</a>, <a href= "http://clojure.org/">Clojure</a> and others.<br />
<a href="http://www.codecommit.com/blog/java/interop-between-java-and-scala">Here</a> is a good post with examples.</p>
<h2>Educational language</h2>
<p>I had 2 habits that I kept practicing during the learning curve of Scala :</p>
<ul>
<li>Going to Wikipedia every while to read more about the new technical terms I passed by; terms like <a href="http://en.wikipedia.org/wiki/First-class_function">Function literals</a>, <a href="http://en.wikipedia.org/wiki/Referential_transparency_%28computer_science%29">Referentially transparent</a>, <a href="http://en.wikipedia.org/wiki/Partial_function">Partial functions</a>, <a href="http://en.wikipedia.org/wiki/Currying">Currying</a> and so many other terms.</li>
<li>Revising my knowledge in other languages to check if these terms are implemented somehow.</li>
</ul>
<p>Both of these two habits made me gain more knowledge and increased the quality of my code through some good practices like: writing pure methods that has no side effect and focusing on the &#8216;what&#8217; part of my code, leaving the &#8216;how&#8217; one to language abstractions..  </p>
<h2>Team</h2>
<p>Scala was designed by <a href="http://people.epfl.ch/martin.odersky">Martin Odersky</a> the man running the Programming Methods Laboratory (LAMP) group at Swiss Federal Institute of Technology in Lausanne (EPFL). Odersky was approached by Sun to write the Java 1.1 compiler, he was the lead developer of javac from Java 1.1 through Java 1.4. Also he is the guy behind Java Generics.<br />
Scala is being maintained by Odersky and his team at EPFL. However there are other talented folks who helped shaping Scala over years, you can check the full list <a href="http://www.Scala-lang.org/node/89">here</a>.</p>
<h2>Roots</h2>
<p>Scala was inspired by many languages:</p>
<ul>
<li>Most of the syntax is coming from Java and C#.</li>
<li>	Other elements where adopted from Java such as: basic types, class libraries, and its execution model.</li>
<li>Its uniform object model was pioneered by Smalltalk.</li>
<li>Its idea of universal nesting is also present in Algol, Simula, and, more recently in Beta and gbeta.</li>
<li>Its uniform access principle for method invocation and field selection comes from Eiffel.</li>
<li>Its approach to functional programming is quite similar in spirit to the ML family of languages, which has SML, OCaml, and F# as prominent members.</li>
<li>Many higher-order functions in Scalaâ€™s standard library are also present in ML or Haskell. </li>
<li>Scalaâ€™s implicit parameters were motivated by Haskellâ€™s type classes. Scalaâ€™s actor-based concurrency library was heavily inspired by Erlang.</li>
<li>The specific idea of treating an infix operator as a function and permitting a function literal (or block) as a parameter, which enables libraries to define control structures can be traced back to Iswim and Smalltalk.</li>
</ul>
<h2>Experts&#8217; Opinions</h2>
<p>This <a href="http://www.infoq.com/news/2009/07/scala-replace-java">article</a> is a very good one showing some for experts&#8217; opinions regarding Scala language. Actually it has some surprises like James Strachan&#8217;s(creator of Groovy language) statement: </p>
<blockquote><p>I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon &#038; Bill Venners back in 2003 I&#8217;d probably have never created Groovy </p></blockquote>
<p>Also I have found these interviews to be very useful:</p>
<ul>
<li><a href="http://on-ruby.blogspot.com/2009/03/beginning-scala-author-interview-with.html">Beginning Scala &#8212; Author Interview with David Pollak</a></li>
<li>  <a href="http://on-ruby.blogspot.com/2009/03/dean-wampler-and-alex-payne-author.html"> Dean Wampler and Alex Payne: Author Interview</a></li>
<li>  <a href="http://on-ruby.blogspot.com/2009/03/author-interview-venkat-subramaniam.html">Author Interview: Venkat Subramaniam</a></li>
</ul>
<hr/>
<strong>At the end of this point I like to sum things up:</strong><br />
I like Scala because it&#8217;s efficient, educational, has better concurrency model, and very good for writing DSLs.<br />
<strong>I also want to share another secret with you:</strong><br />
 I&#8217;m planning to write a book on Scala language, I have an idea at mind and would like to coauthor with any guy from the Scala camp, please ping me if you have the same attention as mine.</p>
<hr/>
<h2>Real World Examples</h2>
<ul>
<li><a href="http://www.artima.com/scalazine/articles/twitter_on_scala.html">Twitter</a></li>
<li> <a href="http://liftweb.net/">Lift</a> framework.</li>
<li><a href="http://www.scala-lang.org/node/1658">Many other</a> examples</li>
</ul>
<h2>Resources</h2>
<ul>
<li><a href="http://www.artima.com/shop/programming_in_scala">Programming in Scala</a> book.</li>
<li><a href="http://www.apress.com/book/view/1430219890">Beginning Scala</a> book.</li>
<li><a href="http://www.scala-lang.org/node/198">Scala reference manuals </a> page, contains very useful free PDFs </li>
<li><a href="http://www.ibm.com/developerworks/views/java/libraryview.jsp?search_by=scala+neward">Scala series</a> on IBM developerWorks website.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.khelll.com/blog/scala/scala-is-my-next-choice/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>Ruby Currying</title>
		<link>http://www.khelll.com/blog/ruby/ruby-currying/</link>
		<comments>http://www.khelll.com/blog/ruby/ruby-currying/#comments</comments>
		<pubDate>Mon, 25 May 2009 04:36:46 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[currying]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=401</guid>
		<description><![CDATA[Update: This post was updated to show the difference between Currying and Partial Functions.
Currying is a concept in Functional Programming that&#8217;s enabled by Higher-order functions. It&#8217;s best described as: the ability to take a function that accepts n parameters and turns it into a composition of n functions each of them take 1 parameter.  [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Update: This post was updated to show the difference between Currying and Partial Functions.</strong><br />
<strong>Currying</strong> is a concept in Functional Programming that&#8217;s enabled by Higher-order functions. It&#8217;s best described as: the ability to take a function that accepts n parameters and turns it into a composition of <code>n</code> functions each of them take 1 parameter.  Check this function <em>f</em> which takes 3 params <em>x</em>,<em>y</em>,<em>z</em></p>
<p><code>f(x,y,z) = 4*x+3*y+2*z</code></p>
<p>Currying means that we can rewrite the function as a composition of 3 functions(a function for each param):</p>
<p><code>f(x)(y)(z) = 2*z+(3*y+(4*x))</code></p>
<p>The direct use of this is what is called <strong>Partial Function</strong> where if you have a function that accepts n parameters then you can generate from it one of more functions with some parameter values already filled in.  Ruby 1.9 comes with support for currying concept(through the Proc#curry method) and this blog post is explaining how you can use it effectively.<br />
I&#8217;m going to walk you through a simple example to explain the concept, however i need to mention few things:<br />
1- The main example is taken from the free <a href="http://www.scala-lang.org/sites/default/files/linuxsoft_archives/docu/files/ScalaByExample.pdf">Scala By Example</a> book(First-Class Functions chapter), however i have replaced recursion calls by simple <code>upto</code> iterators.<br />
2- In Ruby 1.9 you can use block.(*args) just like you use <code>block.call(*args)</code> or <code>block[*args]</code> in Ruby 1.8, so i&#8217;ll stick to  <code>block.(*)</code> notation.<br />
3- I could have used the <code>inject</code> method, but i preferred readability to concise code. </p>
<p>Let&#8217;s start the simple tutorial by adding three methods:<br />
1- A method to sum all integers between two given numbers <code>a</code> and <code>b</code>.<br />
2- A method to sum the squares of all integers between two given numbers <code>a</code> and <code>b</code>.<br />
3- A method to to sum the powers <code>2^n</code> of all integers <code>n</code> between two given numbers <code>a</code> and <code>b</code>.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;">###################################</span>
<span style="color:#008000; font-style:italic;"># Normal definitions</span>
<span style="color:#008000; font-style:italic;">###################################</span>
sum_ints = <span style="color:#CC0066; font-weight:bold;">lambda</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>a,b<span style="color:#006600; font-weight:bold;">|</span>
  s = <span style="color:#006666;">0</span> ; a.<span style="color:#9900CC;">upto</span><span style="color:#006600; font-weight:bold;">&#40;</span>b<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>n<span style="color:#006600; font-weight:bold;">|</span> s <span style="color:#006600; font-weight:bold;">+</span>= n <span style="color:#006600; font-weight:bold;">&#125;</span> ; s 
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
sum_of_squares = <span style="color:#CC0066; font-weight:bold;">lambda</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>a,b<span style="color:#006600; font-weight:bold;">|</span>
  s = <span style="color:#006666;">0</span> ; a.<span style="color:#9900CC;">upto</span><span style="color:#006600; font-weight:bold;">&#40;</span>b<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>n<span style="color:#006600; font-weight:bold;">|</span> s <span style="color:#006600; font-weight:bold;">+</span>= n<span style="color:#006600; font-weight:bold;">**</span><span style="color:#006666;">2</span> <span style="color:#006600; font-weight:bold;">&#125;</span> ;s 
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
sum_of_powers_of_2 = <span style="color:#CC0066; font-weight:bold;">lambda</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>a,b<span style="color:#006600; font-weight:bold;">|</span>
  s = <span style="color:#006666;">0</span> ; a.<span style="color:#9900CC;">upto</span><span style="color:#006600; font-weight:bold;">&#40;</span>b<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>n<span style="color:#006600; font-weight:bold;">|</span> s <span style="color:#006600; font-weight:bold;">+</span>= <span style="color:#006666;">2</span><span style="color:#006600; font-weight:bold;">**</span>n <span style="color:#006600; font-weight:bold;">&#125;</span> ; s 
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">puts</span> sum_ints.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 15</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> sum_of_squares.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 55</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> sum_of_powers_of_2.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 62</span></pre></div></div>

<p>Cool, however if you focus on the 3 methods, you will notice that these methods are all instances of a pattern &Sigma;f(n) for a range of  values a -> b. We can factor out the common pattern by defining a method sum:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;">############################################</span>
<span style="color:#008000; font-style:italic;"># Some refactoring to make some abstraction</span>
<span style="color:#008000; font-style:italic;"># Passing the sum mechanism itself</span>
<span style="color:#008000; font-style:italic;">############################################</span>
&nbsp;
sum = <span style="color:#CC0066; font-weight:bold;">lambda</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>f,a,b<span style="color:#006600; font-weight:bold;">|</span>
  s = <span style="color:#006666;">0</span> ; a.<span style="color:#9900CC;">upto</span><span style="color:#006600; font-weight:bold;">&#40;</span>b<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>n<span style="color:#006600; font-weight:bold;">|</span> s <span style="color:#006600; font-weight:bold;">+</span>= f.<span style="color:#006600; font-weight:bold;">&#40;</span>n<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#125;</span> ; s 
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">puts</span> sum.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">lambda</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> x<span style="color:#006600; font-weight:bold;">&#125;</span>,<span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 15</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> sum.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">lambda</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> x<span style="color:#006600; font-weight:bold;">**</span><span style="color:#006666;">2</span><span style="color:#006600; font-weight:bold;">&#125;</span>,<span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 55</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> sum.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">lambda</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#006666;">2</span><span style="color:#006600; font-weight:bold;">**</span>x<span style="color:#006600; font-weight:bold;">&#125;</span>,<span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 62</span></pre></div></div>

<p>Ok, but what about having the formal definitions for the 3 methods? How can we have those definitions out of the <code>sum</code> method? Well that&#8217;s the use of currying and partial functions, in our case we just need to pass the first param to the <code>sum</code> method to specify what type of sum is it:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;">###################################</span>
<span style="color:#008000; font-style:italic;"># More refactoring using currying</span>
<span style="color:#008000; font-style:italic;"># Currying was added to Ruby 1.9</span>
<span style="color:#008000; font-style:italic;"># Via Proc#curry</span>
<span style="color:#008000; font-style:italic;">###################################</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># generate the currying</span>
currying = sum.<span style="color:#9900CC;">curry</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># Generate the partial functions</span>
sum_ints = currying.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">lambda</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> x<span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
sum_of_squares = currying.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">lambda</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> x<span style="color:#006600; font-weight:bold;">**</span><span style="color:#006666;">2</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
sum_of_powers_of_2 = currying.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">lambda</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#006666;">2</span><span style="color:#006600; font-weight:bold;">**</span>x<span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">puts</span> sum_ints.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 15</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> sum_of_squares.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 55</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> sum_of_powers_of_2.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 62</span></pre></div></div>

<p>That&#8217;s it! I hope I could clarify the use of currying, if not just add your comment here <img src='http://www.khelll.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  </p>
]]></content:encoded>
			<wfw:commentRss>http://www.khelll.com/blog/ruby/ruby-currying/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Ruby and Functional Programming</title>
		<link>http://www.khelll.com/blog/ruby/ruby-and-functional-programming/</link>
		<comments>http://www.khelll.com/blog/ruby/ruby-and-functional-programming/#comments</comments>
		<pubDate>Sun, 24 May 2009 12:28:30 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=351</guid>
		<description><![CDATA[Ruby is known to support the functional paradigm. This article is going to walk you through the Functional Programming page on WikiPedia, to revise the general concepts of functional programming and to explain how Ruby supports them.
According to wikipedia, a functional programming can be described as follows:
In computer science, functional programming is a programming paradigm [...]]]></description>
			<content:encoded><![CDATA[<p>Ruby is known to support the functional paradigm. This article is going to walk you through the Functional Programming <a href="http://en.wikipedia.org/wiki/Functional_programming">page</a> on WikiPedia, to revise the general concepts of functional programming and to explain how Ruby supports them.<br />
According to wikipedia, a functional programming can be described as follows:</p>
<blockquote><p>In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state. Functional programming has its roots in the lambda calculus, a formal system developed in the 1930s to investigate function definition, function application, and recursion. Many functional programming languages can be viewed as embellishments to the lambda calculus.</p></blockquote>
<p>That&#8217;s a clear definition, however and if it&#8217;s not, the following walk through some <strong>concepts</strong> of functional programming should result in a better understanding:  </p>
<h2>Pure functions</h2>
<blockquote><p>In practice, the difference between a mathematical function and the notion of a &#8220;function&#8221; used in imperative programming is that imperative functions can have side effects, changing the value of already calculated computations. Because of this they lack referential transparency, i.e. the same language expression can result in different values at different times depending on the state of the executing program. Conversely, in functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) both times. Eliminating side-effects can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.</p></blockquote>
<p>Pure functions support the mathematical definition of a function:</p>
<p><em> y = f(x)</em></p>
<p>Which means:<br />
1- A function should return the same exact value given the same exact input.<br />
2- A function does one thing exactly(has one clear mission), it has no side effects like changing some other value or write to stream or any other mission rather than its assigned one.</p>
<p>In fact Ruby doesn&#8217;t force you to write pure functions, but certainly it helps you to do so. Actually exercising yourself to write in pure functional style when possible helps you really in many ways:<br />
1- It makes your code clean, readable and self-documenting.<br />
2- It makes your code more &#8220;thread safe&#8221;<br />
3- It helps you more when it comes to TDD.</p>
<p>Let&#8217;s have a look on how Ruby helps you do Pure functional code:</p>
<h3>The <code>!</code> symbol</h3>
<p>Most of Ruby programmers know the <code>!</code> symbol that comes at the end of method names like <code>gsub!</code>, <code>merge!</code> and many other methods. The <code>!</code> symbol means: &#8220;Use it cautiously&#8221;. However If you focus more, you will notice that <strong>most of time</strong>, the <code>!</code> symbol means: &#8220;This is a method that has a side effect; it alters the object which is invoked on!&#8221;.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">s = <span style="color:#996600;">&quot;hello&quot;</span> <span style="color:#008000; font-style:italic;">#=&gt; &quot;hello&quot;</span>
up_s = s.<span style="color:#9900CC;">upcase</span> <span style="color:#008000; font-style:italic;">#=&gt; &quot;HELLO&quot;</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> s.<span style="color:#9900CC;">upcase</span>! <span style="color:#008000; font-style:italic;">#=&gt; &quot;HELLO&quot;</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> s <span style="color:#008000; font-style:italic;">#=&gt; &quot;HELLO&quot;</span></pre></div></div>

<p>As you can see, the <code>upcase!</code> method is not a pure functional method cause it has a side effect, it changes the string itself. On the other hand, the <code>upcase</code> method is a pure functional one as it returns the corresponding value with no other side effects.</p>
<p>On all hows, it&#8217;s highly recommended that you stick to this convention of method naming when you code in Ruby.</p>
<h3>Expressions</h3>
<p><strong>Everything is evaluated as an expression in Ruby</strong>: literals, method calls, variables&#8230; even a control structure has a value. For example you can do this in Ruby:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">if</span> num == <span style="color:#996600;">&quot;one&quot;</span> <span style="color:#9966CC; font-weight:bold;">then</span> val = <span style="color:#006666;">1</span>
<span style="color:#9966CC; font-weight:bold;">elsif</span> num == <span style="color:#996600;">&quot;two&quot;</span> <span style="color:#9966CC; font-weight:bold;">then</span> val = <span style="color:#006666;">2</span>
<span style="color:#9966CC; font-weight:bold;">else</span> <span style="color:#9966CC; font-weight:bold;">then</span> val = <span style="color:#006666;">3</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>But that is a weak use of Ruby&#8217;s power, instead you&#8217;d better do:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">val = <span style="color:#9966CC; font-weight:bold;">if</span> num == <span style="color:#996600;">&quot;one&quot;</span> <span style="color:#9966CC; font-weight:bold;">then</span>   <span style="color:#006666;">1</span>
<span style="color:#9966CC; font-weight:bold;">elsif</span> num == <span style="color:#996600;">&quot;two&quot;</span> <span style="color:#9966CC; font-weight:bold;">then</span>  <span style="color:#006666;">2</span>
<span style="color:#9966CC; font-weight:bold;">else</span> <span style="color:#006666;">3</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<h3>Return value</h3>
<p>Ruby returns the last expression value as the return value of the method invocation, so you don&#8217;t need an explicit <code>return</code> statement.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> greeting<span style="color:#006600; font-weight:bold;">&#40;</span>name<span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#996600;">&quot;Hello #{name}!&quot;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> greeting<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'khelll'</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; &quot;Hello khelll!&quot;</span></pre></div></div>

<p>Together, the auto returned value and evaluating code as expressions are indeed a big support for pure functional code as finally they both serve the fact of having a value out of your method.</p>
<h2>Higher-order functions</h2>
<p>Functions are higher-order when they can take other functions as arguments, and return them as results. This is done in Ruby using lambda and block logic. If you don&#8217;t know how to use blocks, please do yourself a favor and visit this <a href="http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/">comprehensive article</a> by Robert Sosinski.</p>
<p>Blocks in Ruby can help you do very nice things, one of them is ability to add control structure like syntax to your code. Check the following example, where a loop control structure is being defined:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># a trivial example that adds a loop control structure</span>
<span style="color:#008000; font-style:italic;"># it takes a range and yields the passed block.</span>
<span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#CC0066; font-weight:bold;">loop</span><span style="color:#006600; font-weight:bold;">&#40;</span>x,<span style="color:#006600; font-weight:bold;">&amp;</span>b<span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">for</span> i <span style="color:#9966CC; font-weight:bold;">in</span> x <span style="color:#9966CC; font-weight:bold;">do</span>
    b.<span style="color:#9900CC;">call</span><span style="color:#006600; font-weight:bold;">&#40;</span>i<span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># use the above defined method</span>
<span style="color:#CC0066; font-weight:bold;">loop</span><span style="color:#006600; font-weight:bold;">&#40;</span>1..10<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span>
  <span style="color:#CC0066; font-weight:bold;">puts</span> x
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p><a href="http://www.khelll.com/blog/ruby/ruby-and-internal-dsls/">Internal DSLs</a> is also one of the nice things that you can achieve with block syntax in Ruby.</p>
<h3>Currying and Partial Functions</h3>
<p>Higher-order functions enable <strong>Currying</strong>, which the ability to take a function that accepts n parameters and turns it into a composition of n functions each of them take 1 parameter. A direct use of currying is the <strong>Partial Functions</strong> where if you have a function that accepts n parameters then you can generate from it one of more functions with some parameter values already filled in. Ruby 1.9 comes with support for this concept. check the following example:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># defining a proc that sums 2 numbers</span>
plus = <span style="color:#CC0066; font-weight:bold;">lambda</span> <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>a,b<span style="color:#006600; font-weight:bold;">|</span> a <span style="color:#006600; font-weight:bold;">+</span> b<span style="color:#006600; font-weight:bold;">&#125;</span> <span style="color:#008000; font-style:italic;">#=&gt; #&lt;Proc:0x8e236ac@(irb):1 (lambda)&gt; </span>
&nbsp;
<span style="color:#008000; font-style:italic;"># notice the new call to procs in ruby 1.9 using the period symbol</span>
plus.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">3</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 8 </span>
&nbsp;
<span style="color:#008000; font-style:italic;"># i want a modified version of the above proc that fills the first parameter with the value '1'</span>
<span style="color:#008000; font-style:italic;"># so i generate the currying then i use a partial function by supplying the first parameter</span>
<span style="color:#008000; font-style:italic;"># with value '1'</span>
plus_one = plus.<span style="color:#9900CC;">curry</span>.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; #&lt;Proc:0x8dde908&gt;</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># I can use the new proc as normal</span>
plus_one.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 6</span></pre></div></div>

<p>For extended example about currying, check <a href="http://www.khelll.com/blog/ruby/ruby-currying/">Ruby Currying</a> blog post by me <img src='http://www.khelll.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  . </p>
<h2>Type systems and pattern matching</h2>
<p>Pattern matching allows complicated control decisions based on data structure to be expressed in a concise manner. in simpler words, it&#8217;s a data structure based matching. Pure functional languages should support this concept, however and afaik this is still not supported in Ruby, but there are several trials to add this concept. check this <a href="http://etorreborre.blogspot.com/2007/04/pattern-matching-with-ruby.html">blog post</a> by Eric Torreborre.</p>
<h2>Strict versus lazy evaluation</h2>
<p>Strict evaluation always fully evaluates function arguments before invoking the function. Lazy evaluation does not evaluate function arguments unless their values are required to be evaluated. One use of Lazy evaluation is the performance increases due to avoiding unnecessary calculations.</p>
<p>However as the following example shows, Ruby use Strict evaluation strategy:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">print</span> length<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006666;">2</span><span style="color:#006600; font-weight:bold;">+</span><span style="color:#006666;">1</span>, <span style="color:#006666;">3</span><span style="color:#006600; font-weight:bold;">*</span><span style="color:#006666;">2</span>, <span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">/</span><span style="color:#006666;">0</span>, <span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">-</span><span style="color:#006666;">4</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span>ZeroDivisionError: divided by <span style="color:#006666;">0</span></pre></div></div>

<p>The third parameter of the passed array contains a division by zero operation and as Ruby is doing strict evaluation, the above snippet of code will raise an exception.</p>
<h2>Recursion</h2>
<p>Iteration (looping) in functional languages is usually accomplished via recursion. Ruby doesn&#8217;t force you to recursion but it allows you to do so. However following recursion style has it&#8217;s own tax: Performance.<br />
Ruby 1.9 comes with some &#8220;tail call optimizations&#8221;, more <a href="http://www.reddit.com/r/ruby/comments/8lz33/ruby_19_has_tail_call_optimization">here</a>.</p>
<h2>Conclusion</h2>
<p>1- As you can tell, Ruby helps you write in functional style but it doesn&#8217;t force you to it.<br />
2- Writing in functional style enhances your code and makes it more self documented. Actually it will make it more thread-safe also.<br />
3- The main support for FB in ruby comes from the use of blocks and lambdas, also from the fact that everything is evaluated as an expression.<br />
4- Ruby still lack an important aspect of FP: Pattern Matching and Lazy Evaluation.<br />
5- There should be more work on tail recursion optimization, to encourage developers to use recursion.<br />
6- Any other thoughts?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.khelll.com/blog/ruby/ruby-and-functional-programming/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>
