<?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; Ruby</title>
	<atom:link href="http://www.khelll.com/blog/category/ruby/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>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>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>
		<item>
		<title>Delegation in Ruby</title>
		<link>http://www.khelll.com/blog/ruby/delegation-in-ruby/</link>
		<comments>http://www.khelll.com/blog/ruby/delegation-in-ruby/#comments</comments>
		<pubDate>Mon, 27 Apr 2009 02:25:57 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[delegation]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=331</guid>
		<description><![CDATA[This is my first article in http://railsmagazine.com, it was published in issue 1, so basically I&#8217;m just republishing it here again.
&#8220;Separate changeable parts from others that remain the same&#8221; and &#8220;composition is preferred to inheritance&#8221; are 2 common design principles when you start designing in OOP world. However and while the first seems to be [...]]]></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/1">issue 1</a>, so basically I&#8217;m just republishing it here again.</em></p>
<p>&#8220;Separate changeable parts from others that remain the same&#8221; and &#8220;composition is preferred to inheritance&#8221; are 2 common design principles when you start designing in OOP world. However and while the first seems to be logical, a one might wonder why it&#8217;s preferable to use composition over inheritance, and that&#8217;s a logical question, lets answer it via an example:</p>
<p>Let&#8217;s suppose that we have a Robot that has a heat sensor, a one would write a very simple UML:</p>
<p><img src="http://www.khelll.com/public/images/delegation_in_ruby/robot.png" /></p>
<p>This design has several drawbacks:</p>
<p>1.There is a strong probability to have another type of robots that don&#8217;t have heat sensors(breaks the first design principle: separate changeable code from static one).<br />
2.Whenever I want to modify anything related to the heat sensor, I have to change the robot class(breaks the first design principle).<br />
3.Exposure of heat sensor methods to in Robot class.</p>
<p>Let&#8217;s enhance this class a bit:</p>
<p><img src="http://www.khelll.com/public/images/delegation_in_ruby/volcano_robot.png" /></p>
<p>Well, now this is an inheritance based design and it solves the first problem, but it&#8217;s still incapable to solve the other 2 problems related to the heat sensor. Let&#8217;s do another enhancement:</p>
<p><img src="http://www.khelll.com/public/images/delegation_in_ruby/heat_sensor.png"/></p>
<p>Now this is a typical design, based on composition rather than inheritance, where we could solve the above 3 problems, and moreover we gained a new thing:  we can now abstract the HeatSensor for future uses.</p>
<h2>Now what&#8217;s delegation? </h2>
<p>Delegation is the process of delegating functionality to the contained parts.<br />
If you look carefully at the previous figure, you will notice that the VolcanoRobot is still having the 3 methods that are related to the sensor, well those are a wrapper methods, they do nothing but to call the sensor corresponding ones, and that&#8217;s exactly what delegation is, just delegate functionality to the contained parts(delegates).<br />
Delegation comes along with composition to provide a flexible neat solutions like the one we had above, and also it serves the principle &#8220;separate changeable code from static one&#8221; ,but that also comes with a tax: a need of wrapper methods, and extra time needed in processing because of the call of these wrapper methods.</p>
<h2>Ruby and delegation</h2>
<p>Now let&#8217;s have a code example:<br />
We have a multi purpose Robot that has an arm and a heat sensor, the robot does several jobs, like packaging boxes, stacking them and measuring the heat.<br />
we will use composition and delegation as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Robot
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize
    <span style="color:#0066ff; font-weight:bold;">@heat_sensor</span> = HeatSensor.<span style="color:#9900CC;">new</span>
    <span style="color:#0066ff; font-weight:bold;">@arm</span> = RobotArm.<span style="color:#9900CC;">new</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> measure_heat<span style="color:#006600; font-weight:bold;">&#40;</span>scale=<span style="color:#996600;">&quot;c&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0066ff; font-weight:bold;">@heat_sensor</span>.<span style="color:#9900CC;">measure</span><span style="color:#006600; font-weight:bold;">&#40;</span>scale<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> stack<span style="color:#006600; font-weight:bold;">&#40;</span>boxes_number=<span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0066ff; font-weight:bold;">@arm</span>.<span style="color:#9900CC;">stack</span><span style="color:#006600; font-weight:bold;">&#40;</span>boxes_number<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> package
    <span style="color:#0066ff; font-weight:bold;">@arm</span>.<span style="color:#9900CC;">package</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> HeatSensor
  <span style="color:#008000; font-style:italic;">#Celsius or Fahrenheit scale</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> measure<span style="color:#006600; font-weight:bold;">&#40;</span>scale=<span style="color:#996600;">&quot;c&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    t = <span style="color:#CC0066; font-weight:bold;">rand</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">100</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    t = scale==<span style="color:#996600;">&quot;c&quot;</span> ? t : t <span style="color:#006600; font-weight:bold;">*</span> <span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">9</span><span style="color:#006600; font-weight:bold;">/</span><span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;Heat is #{t}° #{scale.upcase}&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> RobotArm
  <span style="color:#9966CC; font-weight:bold;">def</span> stack<span style="color:#006600; font-weight:bold;">&#40;</span>boxes_number=<span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;Stacking #{boxes_number} box(es)&quot;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> package
    <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;Packaging&quot;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
&nbsp;
robo = Robot.<span style="color:#9900CC;">new</span> <span style="color:#008000; font-style:italic;">#=&gt;#&lt;Robot:0xb75131e8 @arm=#&lt;RobotArm:0xb75131ac&gt;, @heat_sensor=#&lt;HeatSensor:0xb75131c0&gt;&gt;</span>
robo.<span style="color:#9900CC;">stack</span> <span style="color:#006666;">2</span> <span style="color:#008000; font-style:italic;">#=&gt;Stacking 2 box(es)</span>
robo.<span style="color:#9900CC;">package</span> <span style="color:#008000; font-style:italic;">#=&gt;Packaging</span>
robo.<span style="color:#9900CC;">measure_heat</span> <span style="color:#008000; font-style:italic;">#=&gt; Heat is 59° C</span></pre></div></div>

<p>As you can see, i have 3 wrapper methods(stack,package and measure_heat) in Robot class that are doing nothing but to call the contained objects corresponding methods.<br />
This is really a nasty thing, specially when there are lots of contained objects.<br />
However there are 2 libs that comes to the rescue to in ruby, Forwardable and Delegate. Let&#8217;s check them one by one.</p>
<h2>Forwardable lib</h2>
<p><a href="http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html">Forwardable lib</a> is library that supports delegation, it has 2 modules Forwardable and SingleForwardable: </p>
<h3>Forwardable module</h3>
<p>The <a href="http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/Forwardable.html">Forwardable</a> module provides delegation of specified methods to a designated object, using the methods <a href="http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/Forwardable.html#M000736">def_delegator</a> and <a href="http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/Forwardable.html#M000735">def_delegators</a>. </p>
<p>def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.</p>
<p>def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.</p>
<p>Let&#8217;s refactor our robot example to make it Forwardable module:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'forwardable'</span>
<span style="color:#9966CC; font-weight:bold;">class</span> Robot
  <span style="color:#008000; font-style:italic;"># Extending provides class methods</span>
  extend <span style="color:#CC00FF; font-weight:bold;">Forwardable</span>
  <span style="color:#008000; font-style:italic;"># Use of  def_delegators</span>
  def_delegators :@arm,:package,:stack
  <span style="color:#008000; font-style:italic;"># Use of  def_delegator</span>
  def_delegator :@heat_sensor, <span style="color:#ff3333; font-weight:bold;">:measure</span> ,:measure_heat
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize
    <span style="color:#0066ff; font-weight:bold;">@heat_sensor</span> = HeatSensor.<span style="color:#9900CC;">new</span>
    <span style="color:#0066ff; font-weight:bold;">@arm</span> = RobotArm.<span style="color:#9900CC;">new</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> HeatSensor
  <span style="color:#008000; font-style:italic;">#Celsius or Fahrenheit scale</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> measure<span style="color:#006600; font-weight:bold;">&#40;</span>scale=<span style="color:#996600;">&quot;c&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    t = <span style="color:#CC0066; font-weight:bold;">rand</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">100</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    t = scale==<span style="color:#996600;">&quot;c&quot;</span> ? t : t <span style="color:#006600; font-weight:bold;">*</span> <span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">9</span><span style="color:#006600; font-weight:bold;">/</span><span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;Heat is #{t}° #{scale.upcase}&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> RobotArm
  <span style="color:#9966CC; font-weight:bold;">def</span> stack<span style="color:#006600; font-weight:bold;">&#40;</span>boxes_number=<span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;Stacking #{boxes_number} box(es)&quot;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> package
    <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;Packaging&quot;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Well, that&#8217;s a neater solution as you can see.</p>
<h3>
SingleForwardable module</h3>
<p>The <a href="http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html">SingleForwardable</a> module provides delegation of specified methods to a designated object, using the methods <a href="http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html#M000732>def_delegator</a> and <a href="http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html#M000731">def_delegators</a>. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">&quot;forwardable&quot;</span>
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">&quot;date&quot;</span>
date = <span style="color:#CC00FF; font-weight:bold;">Date</span>.<span style="color:#9900CC;">today</span> <span style="color:#008000; font-style:italic;">#=&gt; #&lt;Date: 4909665/2,0,2299161&gt;</span>
<span style="color:#008000; font-style:italic;"># Prepare object for delegation</span>
date.<span style="color:#9900CC;">extend</span> <span style="color:#CC00FF; font-weight:bold;">SingleForwardable</span> <span style="color:#008000; font-style:italic;">#=&gt; #&lt;Date: 4909665/2,0,2299161&gt;</span>
<span style="color:#008000; font-style:italic;"># Add delegation for Time.now</span>
date.<span style="color:#9900CC;">def_delegator</span> <span style="color:#ff3333; font-weight:bold;">:Time</span>, <span style="color:#996600;">&quot;now&quot;</span>,<span style="color:#996600;">&quot;with_time&quot;</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> date.<span style="color:#9900CC;">with_time</span> <span style="color:#008000; font-style:italic;">#=&gt;Thu Jan 01 23:03:04 +0200 2009</span></pre></div></div>

<h3>Delegate Lib</h3>
<p><a href="http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html">Delegate lib</a> is another lib that provides delegation, i&#8217;ll explain 2 ways to use it:</p>
<h4>
DelegateClass method</h4>
<p>Use the top level <a href="http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/files/delegate_rb.html#M000406">DelegateClass</a> method which allows you to easily setup delegation through class inheritance. In the following example, I want to make a new class called CurrentDate, which holds the current date and some extra methods, at the same time I&#8217;m delegating to normal date objects:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">&quot;delegate&quot;</span>
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">&quot;date&quot;</span>
<span style="color:#008000; font-style:italic;"># Notice the class definition</span>
<span style="color:#9966CC; font-weight:bold;">class</span> CurrentDate <span style="color:#006600; font-weight:bold;">&lt;</span> DelegateClass<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC00FF; font-weight:bold;">Date</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize
    <span style="color:#0066ff; font-weight:bold;">@date</span> = <span style="color:#CC00FF; font-weight:bold;">Date</span>.<span style="color:#9900CC;">today</span>
    <span style="color:#008000; font-style:italic;"># Pass the object to be delegated to the superclass. </span>
    <span style="color:#9966CC; font-weight:bold;">super</span><span style="color:#006600; font-weight:bold;">&#40;</span>@date<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> to_s
    <span style="color:#0066ff; font-weight:bold;">@date</span>.<span style="color:#9900CC;">strftime</span> <span style="color:#996600;">&quot;%Y/%m/%d&quot;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> with_time
    <span style="color:#CC00FF; font-weight:bold;">Time</span>.<span style="color:#9900CC;">now</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
cdate = CurrentDate.<span style="color:#9900CC;">new</span>
<span style="color:#008000; font-style:italic;"># Notice how delegation works</span>
<span style="color:#008000; font-style:italic;"># Instead of doing cdate.date.day and defining attr_accessor for the date , i'm doing c.day</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> cdate.<span style="color:#9900CC;">day</span> <span style="color:#008000; font-style:italic;">#=&gt;1</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> cdate.<span style="color:#9900CC;">month</span> <span style="color:#008000; font-style:italic;">#=&gt;1</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> cdate.<span style="color:#9900CC;">year</span> <span style="color:#008000; font-style:italic;">#=&gt;2009</span>
<span style="color:#008000; font-style:italic;"># Testing added methods</span>
<span style="color:#008000; font-style:italic;"># to_s</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> cdate <span style="color:#008000; font-style:italic;">#=&gt; 2009/01/01</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> cdate.<span style="color:#9900CC;">with_time</span> <span style="color:#008000; font-style:italic;">#=&gt; Thu Jan 01 23:22:20 +0200 2009</span></pre></div></div>

<h4>SimpleDelegator class</h4>
<p>Use it to delegate to an object that might be changed:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">&quot;delegate&quot;</span>
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">&quot;date&quot;</span>
today = <span style="color:#CC00FF; font-weight:bold;">Date</span>.<span style="color:#9900CC;">today</span> <span style="color:#008000; font-style:italic;">#=&gt; #&lt;Date: 4909665/2,0,2299161&gt;</span>
yesterday = today â€“ <span style="color:#006666;">1</span> <span style="color:#008000; font-style:italic;">#=&gt; #&lt;Date: 4909663/2,0,2299161&gt;</span>
date = <span style="color:#CC00FF; font-weight:bold;">SimpleDelegator</span>.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span>today<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; #&lt;Date: 4909665/2,0,2299161&gt;</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> date <span style="color:#008000; font-style:italic;">#=&gt;2009-01-01</span>
<span style="color:#008000; font-style:italic;"># Use __setobj__ to change the delegate</span>
date.__setobj__<span style="color:#006600; font-weight:bold;">&#40;</span>yesterday<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#008000; font-style:italic;">#=&gt; #&lt;Date: 4909663/2,0,2299161&gt;</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> date <span style="color:#008000; font-style:italic;">#=&gt;2008-12-31</span></pre></div></div>

<p>As you can see, we made 2 objects and then delegated to them consequently.</p>
<h2>
What about Rails?</h2>
<p>Rails adds new functionality called  &#8220;delegate&#8221;:<br />
Which provides a <a href="http://api.rubyonrails.com/classes/Module.html#M000048">delegate</a> class method to easily expose contained objectsâ€™ methods as your own. Pass one or more methods (specified as symbols or strings) and the name of the target object as the final :to option (also a symbol or string). At least one method and the :to option are required. </p>
<p>go to your console and create a dummy project ,then cd to that project, and fire the rails console:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ rails dummy 
â€¦...
$ <span style="color: #7a0874; font-weight: bold;">cd</span> dummy
<span style="color: #007800;">$ruby</span> script<span style="color: #000000; font-weight: bold;">/</span>console
Loading development environment <span style="color: #7a0874; font-weight: bold;">&#40;</span>Rails 2.2.2<span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">&gt;&gt;</span> Person = Struct.new<span style="color: #7a0874; font-weight: bold;">&#40;</span>:name, :address<span style="color: #7a0874; font-weight: bold;">&#41;</span>
=<span style="color: #000000; font-weight: bold;">&gt;</span> Person
<span style="color: #000000; font-weight: bold;">&gt;&gt;</span> class Invoice <span style="color: #000000; font-weight: bold;">&lt;</span> Struct.new<span style="color: #7a0874; font-weight: bold;">&#40;</span>:client<span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">&gt;&gt;</span>   delegate :name, :address, :to =<span style="color: #000000; font-weight: bold;">&gt;</span> :client
<span style="color: #000000; font-weight: bold;">&gt;&gt;</span> end
=<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span>:name, :address<span style="color: #7a0874; font-weight: bold;">&#93;</span>
<span style="color: #000000; font-weight: bold;">&gt;&gt;</span> john_doe = Person.new<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #ff0000;">&quot;John Doe&quot;</span>, <span style="color: #ff0000;">&quot;Vimmersvej 13&quot;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
=<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #666666; font-style: italic;">#&lt;struct Person name=&quot;John Doe&quot;, address=&quot;Vimmersvej 13&quot;&gt;</span>
<span style="color: #000000; font-weight: bold;">&gt;&gt;</span> invoice = Invoice.new<span style="color: #7a0874; font-weight: bold;">&#40;</span>john_doe<span style="color: #7a0874; font-weight: bold;">&#41;</span>
=<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #666666; font-style: italic;">#&lt;struct Invoice client=#&lt;struct Person name=&quot;John Doe&quot;, address=&quot;Vimmersvej 13&quot;&gt;&gt;</span>
<span style="color: #000000; font-weight: bold;">&gt;&gt;</span> invoice.name
=<span style="color: #000000; font-weight: bold;">&gt;</span> John Doe
<span style="color: #000000; font-weight: bold;">&gt;&gt;</span> invoice.address
=<span style="color: #000000; font-weight: bold;">&gt;</span>Vimmersvej <span style="color: #000000;">13</span></pre></div></div>

<p>I strongly urge you to check the whole provided examples in rails API documetation,to check also how to use this effectively with ActiveRecord.</p>
<p>Before I finish this article I want to share you the code of delegate method form rails API documentation, I&#8217;ll add some comments on the code to explain you what is going on:</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:#9966CC; font-weight:bold;">Module</span>
  <span style="color:#008000; font-style:italic;"># Delegate method </span>
  <span style="color:#008000; font-style:italic;"># It expects an array of arguments that contains the methods to be delegated </span>
  <span style="color:#008000; font-style:italic;"># and a hash of options</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> delegate<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">*</span>methods<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#008000; font-style:italic;"># Pop up the options hash from arguments array</span>
    options = methods.<span style="color:#9900CC;">pop</span>
    <span style="color:#008000; font-style:italic;"># Check the availability of the options hash and more specifically the :to option</span>
    <span style="color:#008000; font-style:italic;"># Raises an error if one of them is not there</span>
    <span style="color:#9966CC; font-weight:bold;">unless</span> options.<span style="color:#9900CC;">is_a</span>?<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC00FF; font-weight:bold;">Hash</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&amp;&amp;</span> to = options<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:to</span><span style="color:#006600; font-weight:bold;">&#93;</span>
      <span style="color:#CC0066; font-weight:bold;">raise</span> <span style="color:#CC00FF; font-weight:bold;">ArgumentError</span>, <span style="color:#996600;">&quot;Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to =&gt; :greeter).&quot;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
    <span style="color:#008000; font-style:italic;"># Make sure the :to option follows syntax rules for method names </span>
    <span style="color:#9966CC; font-weight:bold;">if</span> options<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:prefix</span><span style="color:#006600; font-weight:bold;">&#93;</span> == <span style="color:#0000FF; font-weight:bold;">true</span> <span style="color:#006600; font-weight:bold;">&amp;&amp;</span> options<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:to</span><span style="color:#006600; font-weight:bold;">&#93;</span>.<span style="color:#9900CC;">to_s</span> =~ <span style="color:#006600; font-weight:bold;">/</span>^<span style="color:#006600; font-weight:bold;">&#91;</span>^a<span style="color:#006600; font-weight:bold;">-</span>z_<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">/</span>
      <span style="color:#CC0066; font-weight:bold;">raise</span> <span style="color:#CC00FF; font-weight:bold;">ArgumentError</span>, <span style="color:#996600;">&quot;Can only automatically set the delegation prefix when delegating to a method.&quot;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
    <span style="color:#008000; font-style:italic;"># Set the real prefix value </span>
    prefix = options<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:prefix</span><span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#006600; font-weight:bold;">&amp;&amp;</span> <span style="color:#996600;">&quot;#{options[:prefix] == true ? to : options[:prefix]}_&quot;</span>
&nbsp;
   <span style="color:#008000; font-style:italic;"># Here comes the magic of ruby :) </span>
   <span style="color:#008000; font-style:italic;"># Reflection techniques are used here:</span>
   <span style="color:#008000; font-style:italic;"># module_eval is used to add new methods on the fly which:</span>
   <span style="color:#008000; font-style:italic;"># expose the contained methods' objects</span>
    methods.<span style="color:#9900CC;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>method<span style="color:#006600; font-weight:bold;">|</span>
      module_eval<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;def #{prefix}#{method}(*args, &amp;block)<span style="color:#000099;">\n</span>#{to}.__send__(#{method.inspect}, *args, &amp;block)<span style="color:#000099;">\n</span>end<span style="color:#000099;">\n</span>&quot;</span>, <span style="color:#996600;">&quot;(__DELEGATION__)&quot;</span>, <span style="color:#006666;">1</span><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>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>That&#8217;s it for this article, we have covered 5 points:</p>
<p>1-Composition vs inheritance.<br />
2-What delegation is, and why it&#8217;s used.<br />
3-Ruby Forwardable lib.<br />
4-Ruby Delegate lib.<br />
5-Rails delegate method.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.khelll.com/blog/ruby/delegation-in-ruby/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>C++ passes by reference, Java and Ruby don&#8217;t</title>
		<link>http://www.khelll.com/blog/ruby/c-passes-by-reference-java-and-ruby-dont/</link>
		<comments>http://www.khelll.com/blog/ruby/c-passes-by-reference-java-and-ruby-dont/#comments</comments>
		<pubDate>Wed, 22 Apr 2009 08:17:42 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=316</guid>
		<description><![CDATA[I got a lot of comments for the previous article, that was explaining how Ruby passes by value, just like Java does.
I thought that showing a simple example implemented  in C++, Java and Ruby will clarify the idea. In the following lines, we will make swap functionality in 3 languages, and demonstrate that neither [...]]]></description>
			<content:encoded><![CDATA[<p>I got a lot of comments for the <a href="http://www.khelll.com/blog/ruby/ruby-pass-by-value-or-by-reference/">previous article</a>, that was explaining how Ruby passes by value, just like Java does.</p>
<p>I thought that showing a simple example implemented  in C++, Java and Ruby will clarify the idea. In the following lines, we will make swap functionality in 3 languages, and demonstrate that neither Java nor Ruby passes by reference.</p>
<p>C++</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include &lt;iostream&gt;</span>
<span style="color: #0000ff;">using</span> <span style="color: #0000ff;">namespace</span> std<span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">class</span> Point <span style="color: #008000;">&#123;</span>
<span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
    <span style="color: #0000ff;">double</span> x, y<span style="color: #008080;">;</span>
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
&nbsp;
    Point<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">double</span> x, <span style="color: #0000ff;">double</span> y<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>x <span style="color: #000080;">=</span> x<span style="color: #008080;">;</span>
        this<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>y <span style="color: #000080;">=</span> y<span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">void</span> print<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;x = &quot;</span> <span style="color: #000080;">&lt;&lt;</span> x <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;, y = &quot;</span> <span style="color: #000080;">&lt;&lt;</span> y <span style="color: #000080;">&lt;&lt;</span> endl<span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #666666;">// Parameters are passed by reference</span>
&nbsp;
<span style="color: #0000ff;">void</span> swap<span style="color: #008000;">&#40;</span>Point <span style="color: #000040;">&amp;</span>p1, Point <span style="color: #000040;">&amp;</span>p2<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    Point temp <span style="color: #000080;">=</span> p1<span style="color: #008080;">;</span>
    p1 <span style="color: #000080;">=</span> p2<span style="color: #008080;">;</span>
    p2 <span style="color: #000080;">=</span> temp<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    <span style="color: #666666;">//initializing the points</span>
    Point val1<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">5</span>, <span style="color: #0000dd;">10</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    Point val2<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">20</span>, <span style="color: #0000dd;">40</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #666666;">//printing their values</span>
    <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Before Passing By Reference&quot;</span> <span style="color: #000080;">&lt;&lt;</span> endl<span style="color: #008080;">;</span> val1.<span style="color: #007788;">print</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> val2.<span style="color: #007788;">print</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #666666;">//swaping, passing by referecne</span>
    swap<span style="color: #008000;">&#40;</span>val1, val2<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #666666;">//printing the values again</span>
    <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;After Passing By Reference&quot;</span> <span style="color: #000080;">&lt;&lt;</span> endl<span style="color: #008080;">;</span> val1.<span style="color: #007788;">print</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> val2.<span style="color: #007788;">print</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Output:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ .<span style="color: #000000; font-weight: bold;">/</span>passcpp
Before Passing By Reference
x = <span style="color: #000000;">5</span>, y = <span style="color: #000000;">10</span>
x = <span style="color: #000000;">20</span>, y = <span style="color: #000000;">40</span>
After Passing By Reference
x = <span style="color: #000000;">20</span>, y = <span style="color: #000000;">40</span>
x = <span style="color: #000000;">5</span>, y = <span style="color: #000000;">10</span></pre></div></div>

<p>Java</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> <span style="color: #003399;">Point</span> <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">double</span> x,  y<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Point</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">double</span> x, <span style="color: #000066; font-weight: bold;">double</span> y<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">x</span> <span style="color: #339933;">=</span> x<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">y</span> <span style="color: #339933;">=</span> y<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> toString<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #003399;">String</span>.<span style="color: #006633;">format</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;x = %.2f , y = %.2f&quot;</span>, x, y<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> swap<span style="color: #009900;">&#40;</span><span style="color: #003399;">Point</span> p1,<span style="color: #003399;">Point</span> p2<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">Point</span> temp <span style="color: #339933;">=</span> p1<span style="color: #339933;">;</span>
        p1 <span style="color: #339933;">=</span> p2<span style="color: #339933;">;</span>
        p2 <span style="color: #339933;">=</span> temp<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> args<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">//initializing the points</span>
        <span style="color: #003399;">Point</span> var1 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Point</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">5</span>, <span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">Point</span> var2 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Point</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">20</span>, <span style="color: #cc66cc;">40</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #666666; font-style: italic;">//printing their values</span>
        <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Before Passing<span style="color: #000099; font-weight: bold;">\n</span>%s<span style="color: #000099; font-weight: bold;">\n</span>%s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>, var1, var2<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #666666; font-style: italic;">// //swaping, passing by reference value, aka: pass by value</span>
        swap<span style="color: #009900;">&#40;</span>var1,var2<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #666666; font-style: italic;">//printing the values again</span>
        <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;After Passing<span style="color: #000099; font-weight: bold;">\n</span>%s<span style="color: #000099; font-weight: bold;">\n</span>%s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>, var1, var2<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Output:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ java Point
Before Passing By Reference
x = <span style="color: #000000;">5.00</span> , y = <span style="color: #000000;">10.00</span>
x = <span style="color: #000000;">20.00</span> , y = <span style="color: #000000;">40.00</span>
After Passing By Reference
x = <span style="color: #000000;">5.00</span> , y = <span style="color: #000000;">10.00</span>
x = <span style="color: #000000;">20.00</span> , y = <span style="color: #000000;">40.00</span></pre></div></div>

<p>Ruby</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Point
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize<span style="color:#006600; font-weight:bold;">&#40;</span>x,y<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0066ff; font-weight:bold;">@x</span>,@y = x,y
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> to_s
    <span style="color:#996600;">&quot;x = #{@x} , y = #{@y}&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;">def</span> swap<span style="color:#006600; font-weight:bold;">&#40;</span>p1,p2<span style="color:#006600; font-weight:bold;">&#41;</span>
  p1,p2 = p2,p1
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#008000; font-style:italic;">#initializing the points</span>
var1 = Point.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">5</span>,<span style="color:#006666;">10</span><span style="color:#006600; font-weight:bold;">&#41;</span>
var2 = Point.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">20</span>,<span style="color:#006666;">40</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#008000; font-style:italic;">#printing their values</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;Before Passing&quot;</span> , var1, var2
<span style="color:#008000; font-style:italic;"># //swaping, passing by reference value, aka: pass by value</span>
swap var1,var2
<span style="color:#008000; font-style:italic;">#printing the values again</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;After Passing&quot;</span> , var1, var2</pre></div></div>

<p>Output:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ ruby passruby.rb
Before Passing By Reference
x = <span style="color: #000000;">5</span> , y = <span style="color: #000000;">10</span>
x = <span style="color: #000000;">20</span> , y = <span style="color: #000000;">40</span>
After Passing By Reference
x = <span style="color: #000000;">5</span> , y = <span style="color: #000000;">10</span>
x = <span style="color: #000000;">20</span> , y = <span style="color: #000000;">40</span></pre></div></div>

<p>As you can notice, in c++ example, passing by reference, will do the swap successfully.<br />
Java and Ruby both don&#8217;t pass by reference, instead they pass a copy of the reference, which is a value finally, and so the swap fails, as swapping the copies doesn&#8217;t swap the original passed objects.</p>
<p>Please note also that in Java, primitive types are passed by their values directly and no need for any kind of references copies.The same case applies for Ruby, with immediate types(int, char&#8230;).</p>
<p>According to the previous 2 facts, we conclude that neither Java nor Ruby passes by reference, instead, both pass by value.</p>
<p>I think that fact that Ruby MRI is using C means they can&#8217;t use references, and so they are using pointers, and that explains why swap fails. </p>
<p>I hope that the idea is clear now.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.khelll.com/blog/ruby/c-passes-by-reference-java-and-ruby-dont/feed/</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
	</channel>
</rss>
