<?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>Arnab&#039;s Universe &#187; programming</title>
	<atom:link href="http://www.arnab-deka.com/posts/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.arnab-deka.com/posts</link>
	<description>(and all the parallel ones)</description>
	<lastBuildDate>Tue, 06 Dec 2011 04:10:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Quick howto on accessing Rails Properties</title>
		<link>http://www.arnab-deka.com/posts/2011/04/quick-howto-accessing-rails-properties/</link>
		<comments>http://www.arnab-deka.com/posts/2011/04/quick-howto-accessing-rails-properties/#comments</comments>
		<pubDate>Sat, 09 Apr 2011 04:52:15 +0000</pubDate>
		<dc:creator>Arnab</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[tech]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[rubyonrails]]></category>

		<guid isPermaLink="false">http://www.arnab-deka.com/posts/?p=525</guid>
		<description><![CDATA[When you create a new Rails app the default static page (public/index.html) page shows a lot of details about the app. Here&#8217;s a quick how-to show these details (the idea is to probably show these on a /ping route (or a debug parameter on any page maybe) &#8211; so you can quickly monitor your app [...]]]></description>
			<content:encoded><![CDATA[<p>When you create a new Rails app the default static page (public/index.html) page shows a lot of details about the app. Here&#8217;s a quick how-to show these details (the idea is to probably show these on a /ping route (or a debug parameter on any page maybe) &#8211; so you can quickly monitor your app &#8211; it&#8217;s state, active_record state etc.).</p>
<p><strong>Rails 3</strong>: browse the <a href="https://github.com/rails/rails/blob/v3.0.6/railties/lib/rails/info.rb">source-code at railties/lib/rails/info.rb</a></p>
<p>Or see:<br />
<script src="https://gist.github.com/911091.js?file=rails_306_properties.rb"></script></p>
<p><strong>Rails 2</strong>: browse the <a href="https://github.com/rails/rails/blob/v2.0.2/railties/builtin/rails_info/rails/info.rb">source-code at railties/builtin/rails_info/rails/info.rb</a></p>
<p>Or see:<br />
<script src="https://gist.github.com/911091.js?file=rails_202_properties.rb"></script></p>
<p>Till the next time&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arnab-deka.com/posts/2011/04/quick-howto-accessing-rails-properties/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Notes on Emacs + CL + Clojure + Slime&#8230;</title>
		<link>http://www.arnab-deka.com/posts/2010/12/notes-on-emacs-cl-clojure-slime/</link>
		<comments>http://www.arnab-deka.com/posts/2010/12/notes-on-emacs-cl-clojure-slime/#comments</comments>
		<pubDate>Thu, 30 Dec 2010 08:35:14 +0000</pubDate>
		<dc:creator>Arnab</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[cl]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[commonlisp]]></category>
		<category><![CDATA[emacs]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[integration]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[osx]]></category>
		<category><![CDATA[setup]]></category>
		<category><![CDATA[slime]]></category>
		<category><![CDATA[swank]]></category>

		<guid isPermaLink="false">http://www.arnab-deka.com/posts/?p=517</guid>
		<description><![CDATA[How to setup Emacs on a Mac to work with Clojure and CommonLisp, integrating with slime and swank.]]></description>
			<content:encoded><![CDATA[<p>After a day of struggling finally Emacs+CL+Clojure+Slime setup is working. I noted it all in the <a href="http://www.arnab-deka.com/posts/notes/emacs-setup/">notes section</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arnab-deka.com/posts/2010/12/notes-on-emacs-cl-clojure-slime/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quick MacBook setup</title>
		<link>http://www.arnab-deka.com/posts/2010/03/quick-macbook-setup/</link>
		<comments>http://www.arnab-deka.com/posts/2010/03/quick-macbook-setup/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 05:33:16 +0000</pubDate>
		<dc:creator>Arnab</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[addons]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[apps]]></category>
		<category><![CDATA[firefox]]></category>
		<category><![CDATA[installing]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[setup]]></category>
		<category><![CDATA[textmate]]></category>

		<guid isPermaLink="false">http://www.arnab-deka.com/posts/?p=463</guid>
		<description><![CDATA[Just put in my notes about setting up a MacBook in the notes section here. I&#8217;ll keep updating &#8211; please add your thoughts in!]]></description>
			<content:encoded><![CDATA[<p>Just put in my notes about setting up a MacBook in <a title="MacBook setup" href="http://www.arnab-deka.com/posts/notes/macbook-setup">the notes section here</a>. I&#8217;ll keep updating &#8211; please add your thoughts in!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arnab-deka.com/posts/2010/03/quick-macbook-setup/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Installing GLPK on a Mac</title>
		<link>http://www.arnab-deka.com/posts/2010/02/installing-glpk-on-a-mac/</link>
		<comments>http://www.arnab-deka.com/posts/2010/02/installing-glpk-on-a-mac/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 22:58:40 +0000</pubDate>
		<dc:creator>Arnab</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[gnu]]></category>
		<category><![CDATA[install]]></category>
		<category><![CDATA[linear-programming]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[maths]]></category>
		<category><![CDATA[open-source]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false">http://www.arnab-deka.com/posts/?p=435</guid>
		<description><![CDATA[Obsolation note: Thanks to Dave Coleman&#8217;s comment I found out that glpk is available through homebrew now! So you just need these 2 steps to get glpk now: homebrew brew install glpk If you still want to read on, the old way is still here&#8230; So you want copy-paste instructions to install GLPK on your [...]]]></description>
			<content:encoded><![CDATA[<blockquote>
<h2> Obsolation note:</h2>
<p> Thanks to <a href="#comment-2787">Dave Coleman&#8217;s comment</a> I found out that glpk is available through homebrew now! So you just need these 2 steps to get glpk now:</p>
<ol>
<li><a href="http://mxcl.github.com/homebrew/" title="homebrew" target="_blank">homebrew</a></li>
<li><code>brew install glpk</code></li>
</ol>
<p>If you still want to read on, the old way is still here&#8230;
</p></blockquote>
<p>So you want copy-paste instructions to install <a href="http://www.gnu.org/software/glpk">GLPK</a> on your Macbook? Here are the steps:</p>
<ol>
<li>Download the latest version of GLPK from <a href="http://www.gnu.org/software/glpk/#downloading">http://www.gnu.org/software/glpk/#downloading</a>
  </li>
<li><em>Optional:</em> Follow the instructions to verify the download (you might need to get GNU Privacy Guard or gpg for this. You can get it at <a href="http://gnupg.org">http://gnupg.org</a>)
  </li>
<li>Say it&#8217;s downloaded to your &#8220;Downloads&#8221; directory, go there and execute the following commands (using the terminal)
<pre class="brush: sh">
cd ~/Downloads
tar -xzf glpk-4.43.tar.gz
./configure --prefix=/usr/local # see note [1]
make
sudo make install
    </pre>
</li>
<li>At this point, you should have GLPK installed. Verify it:
<pre class="brush: sh">
which glpsol
/usr/local/bin/glpsol
    </pre>
</li>
<li>&#8230; and try help:
<pre class="brush: sh">
glpsol --help
    </pre>
</li>
</ol>
<p>Now that you are all set-up, read up this excellent introduction using GLPK: <a href="http://www.ibm.com/developerworks/linux/library/l-glpk1">http://www.ibm.com/developerworks/linux/library/l-glpk1</a></p>
<p>Notes:<br />
  [1]: HiveLogic article on <a href="http://hivelogic.com/articles/using_usr_local">why using /usr/local is better</a><br />
  [2] If you want MySQL support (or something &#8220;extra&#8221;) check out the INSTALL file in the package</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arnab-deka.com/posts/2010/02/installing-glpk-on-a-mac/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Russian Peasant Multiplication in Ruby</title>
		<link>http://www.arnab-deka.com/posts/2010/02/russian-peasant-multiplication-in-ruby/</link>
		<comments>http://www.arnab-deka.com/posts/2010/02/russian-peasant-multiplication-in-ruby/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 21:41:50 +0000</pubDate>
		<dc:creator>Arnab</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[maths]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.arnab-deka.com/posts/?p=426</guid>
		<description><![CDATA[Simple implementation of Russian Peasant Multiplication in Ruby]]></description>
			<content:encoded><![CDATA[<p>Russian Peasant Multiplication: a very simple and elegant way to multiple.</p>
<p>Read more: <a href="http://mathforum.org/dr.math/faq/faq.peasant.html">School-boy example of how and why it works</a> and about <a href="http://en.wikipedia.org/wiki/Ancient_Egyptian_multiplication">Ancient Egyptian Multiplication on wikipedia</a></p>
<p>So here&#8217;s my simple implementation: (or as a <a href="http://gist.github.com/290219">gist on github</a>)</p>
<pre class="brush: ruby">
module RussianPeasantMultiplication
  def russian_peasant_multiply(b)
    numbers_to_add = []
    a, b = [self, b].sort #So we have the smaller number as the first

    negative_operands = [a, b].select { |n| n &lt; 0 }
    result_should_be_negative = negative_operands.size.odd? # or negative_operands.size == 1

    # Now get the absoultes
    a, b = [a, b].map { |n| n.abs }

    while( a &gt; 1 )
      a = a &gt;&gt; 1 # halv it
      b = b &lt; &lt; 1 # double it
      if a.odd? # or (a % 2 == 0 )
        numbers_to_add &lt;&lt; b
      else
      end
    end
    result = numbers_to_add.inject(0) { |sum, n| sum += n }
    result = result * -1 if result_should_be_negative
    result
  end
end

class Integer
  include RussianPeasantMultiplication
end

# Tests
require &quot;test/unit&quot;

class TestInteger &lt; Test::Unit::TestCase
  def test_russian_peasant_multiply
    assert_equal(22 * 70, 22.russian_peasant_multiply(70))
  end

  def test_russian_peasant_multiply_for_negative_numbers
    assert_equal(-22 * 70, -22.russian_peasant_multiply(70))
  end

  def test_russian_peasant_multiply_for_negative_arguments
    assert_equal(22 * -70, 22.russian_peasant_multiply(-70))
  end

  def test_russian_peasant_multiply_for_negative_numbers_and_arguments
    assert_equal(-22 * -70, -22.russian_peasant_multiply(-70))
  end

  def test_russian_peasant_multiply_for_zero
    assert_equal(0 * -70, 0.russian_peasant_multiply(-70))
  end

  def test_russian_peasant_multiply_for_zero_arguments
    assert_equal(-22 * 0, -22.russian_peasant_multiply(0))
  end

  def test_russian_peasant_multiply_for_zero_numbers_and_arguments
    assert_equal(0 * 0, 0.russian_peasant_multiply(0))
  end
end
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.arnab-deka.com/posts/2010/02/russian-peasant-multiplication-in-ruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails: Table join with specified fields in select</title>
		<link>http://www.arnab-deka.com/posts/2009/11/rails-join-with-select/</link>
		<comments>http://www.arnab-deka.com/posts/2009/11/rails-join-with-select/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 04:15:52 +0000</pubDate>
		<dc:creator>Arnab</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[active_record]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[rubyonrails]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://www.arnab-deka.com/posts/?p=417</guid>
		<description><![CDATA[Figured this out after a lot of monkeying-around (I mean script/console). Situation: I have two tables (Revisions has_many Inputs) I can load Revisions and then for each I can find Inputs, but quickly found out that for my situation, it leads to a lot of queries. So I want to load the required fields from [...]]]></description>
			<content:encoded><![CDATA[<p>Figured this out after a lot of monkeying-around (I mean script/console).</p>
<p>Situation:</p>
<ul>
<li>I have two tables (Revisions has_many Inputs)</li>
<li>I can load Revisions and then for each I can find Inputs, but  quickly found out that for my situation, it leads to a lot of queries. So I want to load the required fields from both tables together</li>
</ul>
<p>:joins is the only way to do this, using :includes does NOT respect the select clause. Here is the gist I created:<br />
<script src="http://gist.github.com/223925.js"></script></p>
<p>Admittedly, this is hacky, too hacky for my comfort. Comment/suggest a better/cleaner solution?</p>
<p>Note: Found out that there is a gem to do this: <a href="http://code.google.com/p/ar-select-with-include/">ar-select-with-include</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.arnab-deka.com/posts/2009/11/rails-join-with-select/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>#songsincode (twitter geek fun)</title>
		<link>http://www.arnab-deka.com/posts/2009/08/songsincode-twitter-geek-fun/</link>
		<comments>http://www.arnab-deka.com/posts/2009/08/songsincode-twitter-geek-fun/#comments</comments>
		<pubDate>Sat, 22 Aug 2009 00:11:39 +0000</pubDate>
		<dc:creator>Arnab</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[hashtags]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[trends]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[web2.0]]></category>

		<guid isPermaLink="false">http://www.arnab-deka.com/posts/?p=385</guid>
		<description><![CDATA[This blog is about twitter hastags. To learn more about twitter hashtags, go here. So #songsincode has been ruling the twitter trends for a day now). Didn&#8217;t follow it? No worries &#8211; here&#8217;s a recent blog with some good (early) ones. Basically, it was the most fun I have had reading hashtags. Today, after lunch [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>
This blog is about twitter hastags. To learn more about twitter hashtags, go <a href="http://twitter.pbworks.com/Hashtags">here</a>.
</p></blockquote>
<p>So #songsincode has been <a href="http://twitter.com/#search?q=%23songsincode">ruling the twitter trends</a> for a day now). Didn&#8217;t follow it? No worries &#8211; <a href="http://www.sitepoint.com/blogs/2009/08/21/geeks-just-wanna-have-fun-songsincode/">here&#8217;s a recent blog</a> with some good (early) ones.</p>
<p>Basically, it was the most fun I have had reading hashtags. Today, after lunch I took a plunge too <img src='http://www.arnab-deka.com/posts/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>Original <a href="http://twitter.com/arnab_deka/status/3460700079">tweet here</a>:</p>
<pre class="brush: ruby">
(you.breath + you.move).each { i.missing(you) }
</pre>
<p>Original <a href="http://twitter.com/arnab_deka/status/3460883623">tweet here</a>:</p>
<pre class="brush: ruby">
while ( time(you.reverse) &lt; = 1.minute )
  i = you.steps_behind(2)
end
</pre>
<p>Oh don&#8217;t tell me I was so bad you could not even guess the songs (<a href="http://www.amazon.com/Every-Breath-You-Take/dp/B000W299VM/ref=sr_1_2?ie=UTF8&#038;s=dmusic&#038;qid=1250899720&#038;sr=8-2">Every Breath You Take and <a href="http://www.youtube.com/watch?v=qv829hUuYAM">Two Steps Behind</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arnab-deka.com/posts/2009/08/songsincode-twitter-geek-fun/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Guarded logging in Ruby?</title>
		<link>http://www.arnab-deka.com/posts/2009/08/guarded-logging-in-ruby/</link>
		<comments>http://www.arnab-deka.com/posts/2009/08/guarded-logging-in-ruby/#comments</comments>
		<pubDate>Fri, 07 Aug 2009 17:26:24 +0000</pubDate>
		<dc:creator>Arnab</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[benchmarking]]></category>
		<category><![CDATA[best-practices]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.arnab-deka.com/posts/?p=366</guid>
		<description><![CDATA[talking about and simple-benchmarking "guarded logging", a Java best practice in Ruby's context.]]></description>
			<content:encoded><![CDATA[<p>Assuming you know about &#8220;guarded logging&#8221;, a Java logging best practise. If not, get an overview in <a href="http://publib.boulder.ibm.com/infocenter/ledoc/v6r11/index.jsp?topic=/com.ibm.rcp.tools.doc.appdev/serviceability_java.util.loggingbestpractices.html">this IBM article</a> or in <a href="http://www.burlesontech.com/wiki/display/btg/Java+Logging+Standards+and+Guidelines">this blog</a>.</p>
<p>Basically it is the practice of checking if a particular log message will indeed be outputted to the log (based on the severity level) before calling the log statement. This is a performance improvement.</p>
<pre class="brush: java">
// Java example
if( logger.isLoggable(Level.INFO) ) {
  logger.info( &quot;this is a &quot; + &quot;info&quot; + &quot;message&quot; );
}
</pre>
<p>So I heard from one of my colleagues that Ruby&#8217;s logging performance can also be improved the same way, by putting the message in a block (instead of just passing it as an string arg to the method):</p>
<pre class="brush: ruby">
  @logger.debug { &quot;this is a &quot; + &quot;debug&quot; + &quot;message&quot; }
</pre>
<p>See various ways to log a message at the <a href="http://www.ruby-doc.org/stdlib/libdoc/logger/rdoc/">ruby-docs</a> (search for &#8220;How to log a message&#8221; in that page).<br />
I looked into the source-code and, just like in Java, the first thing that is done is to check the severity and return (true) if the severity is higher than the message&#8217;s. So like in Java, it should not have any effect (except creating the strings etc.).</p>
<p>Just to test it out, I wrote a benchmark test:</p>
<pre class="brush: ruby">
require &#039;benchmark&#039;
require &#039;logger&#039;

class LoggerBenchmark
  def initialize
    @logger = Logger.new(&quot;/dev/null&quot;)
  end

  def benchmark
    n = 10000
    # I use bmbm method and not bm here
    # so the effects of initializing etc. are abstracted away
    Benchmark.bmbm do |x|
      x.report(&quot;with block&quot;) do
        n.times do |i|
          # trying to do *some* arithmetic here
          # so there is *some* work for string-creation
          @logger.warn { &quot;logging with block - #{rand * 1000 % i}&quot; }
        end
      end

      x.report(&quot;with string&quot;) do
        n.times do |i|
          @logger.warn &quot;logging with string - #{rand * 1000 % i}&quot;
        end
      end

      x.report(&quot;with severity check&quot;) do
        n.times do |i|
          if @logger.warn?
            @logger.warn(&quot;logging with severity check - #{rand * 1000 % i}&quot;)
          end
        end
      end

    end
  end
end

LoggerBenchmark.new.benchmark
</pre>
<p>Here&#8217;s what I noticed:</p>
<ul>
<li>with n (the number of logging calls) set to < = 10,000, there was really no difference between the three ways:
<pre class="brush: sh">
$ time ruby logger_benchmark.rb
Rehearsal &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;
with block            1.340000   0.160000   1.500000 (  1.500111)
with string           0.740000   0.110000   0.850000 (  0.845971)
with severity check   0.650000   0.080000   0.730000 (  0.736908)
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212; total: 3.080000sec

                                  user     system      total        real
with block            0.670000   0.100000   0.770000 (  0.765206)
with string           0.640000   0.080000   0.720000 (  0.715421)
with severity check   0.660000   0.080000   0.740000 (  0.733024)
ruby logger_benchmark.rb  4.72s user 0.62s system 99% cpu 5.351 total
</pre>
</li>
</li>
<li>with n set to 100,000: It looked like the simplest way to log (with a string-arg) still performs the best:
<pre class="brush: sh">
$ time ruby logger_benchmark.rb
Rehearsal ---------------------------------------------------------------
with block            7.630000   1.030000   8.660000 (  8.669890)
with string           6.410000   0.840000   7.250000 (  7.270509)
with severity check   6.570000   0.890000   7.460000 (  7.472230)
----------------------------------------------------- total: 23.370000sec

                                  user     system      total        real
with block            6.760000   0.930000   7.690000 (  7.697947)
with string           6.320000   0.870000   7.190000 (  7.190802)
with severity check   6.460000   0.930000   7.390000 (  7.394368)
ruby logger_benchmark.rb  40.20s user 5.50s system 99% cpu 45.755 total
    </pre>
</li>
</ul>
<p>Final takeaway: it really does not make that big a difference and keeping it simple (with a string-arg) should work. If you are worried about performance, this probably is not a trick that will give you a big bang for the buck.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arnab-deka.com/posts/2009/08/guarded-logging-in-ruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby dup vs clone</title>
		<link>http://www.arnab-deka.com/posts/2009/07/ruby-dup-vs-clone/</link>
		<comments>http://www.arnab-deka.com/posts/2009/07/ruby-dup-vs-clone/#comments</comments>
		<pubDate>Wed, 29 Jul 2009 02:01:24 +0000</pubDate>
		<dc:creator>Arnab</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[tech]]></category>

		<guid isPermaLink="false">http://www.arnab-deka.com/posts/?p=313</guid>
		<description><![CDATA[A bit about Ruby's clone and dup methods. They both create shallow copies, so what is the difference between them?]]></description>
			<content:encoded><![CDATA[<p>I have had this question about the difference between Ruby&#8217;s <code>clone</code> and <code>dup</code> method multiple times now. And I have always had this fuzzy feeling that &#8220;they are almost the same thing&#8221;. Today my colleague asked it again and I decided to dig it out. Here&#8217;s what <a href="http://ruby-doc.org/core/classes/Object.html">Ruby API docs</a> say about them:</p>
<blockquote><p>
<strong>Object#clone</strong><br />
Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. Copies the frozen and tainted state of obj.
</p></blockquote>
<blockquote><p>
<strong>Object#dup</strong><br />
Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. See also the discussion under Object#clone. In general, clone and dup may have different semantics in descendant classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendant object to create the new instance.</p>
<p>This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.
</p></blockquote>
<p>So in essence, both produce shallow-copies of the object. clone copies the frozen <i>and</i> tainted state while dup copies only the tainted state. Even after reading that documentation twice, it&#8217;s still murky in my head (probably coz I have not had <i>a chance</i> to write code to notice the frozen or tainted state specifically.)</p>
<p>Here&#8217;s a gem from ruby-talk that Google brought up: <a href="http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/6328">http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/6328</a>. So Matz says:</p>
<blockquote><p>`clone&#8217; copies everything; internal state, singleton methods, etc.<br />
`dup&#8217; copies object contents only (plus taintness status).
</p></blockquote>
<p>And so I wrote a bit of code to see it myself (and thus remember it). Here&#8217;s a very simple Person class:</p>
<pre class="brush: ruby">
class Person
  attr_accessor :name
end
</pre>
<p>Now we instantiate a Person object (p) and add then an singleton method on the new object (p) to say hi:</p>
<pre class="brush: ruby">
p = Person.new
p.name = &quot;The Man&quot;

# now add a singleton method on p:
def p.say_hi
  &quot;&#039;sup&quot;
end
</pre>
<p>See that it&#8217;s all working:</p>
<pre class="brush: ruby">
irb(main):014:0&gt; puts p.inspect
#&lt;person :0xb7e83340 @name=&quot;The Man&quot;&gt;
=&gt; nil
irb(main):015:0&gt; puts p.say_hi
&#039;sup
=&gt; nil
</pre>
<p>Now create a clone and a dup of it:</p>
<pre class="brush: ruby">
the_clone = p.clone
the_dup = p.dup
</pre>
<p>Both the clone and the dup have the same instance variables (which are shallow-copies BTW), but only the clone has the singleton method (say_hi) in it:</p>
<pre class="brush: ruby">
irb(main):018:0&gt; the_clone.name
=&gt; &quot;The Man&quot;
irb(main):019:0&gt; the_dup.name
=&gt; &quot;The Man&quot;
irb(main):020:0&gt; the_clone.say_hi
=&gt; &quot;&#039;sup&quot;
irb(main):021:0&gt; the_dup.say_hi
NoMethodError: undefined method `say_hi&#039; for
(Person :0xb7e83340 @name=&quot;The Man&quot;)
        from (irb):21
        from :0
irb(main):022:0&gt;
</pre>
<p>So that makes me feel that clone has to do more work than dup does. Hence dup might be more beneficial for performance compared to clone (unless you really need to use clone). Comments are welcome!</person>
]]></content:encoded>
			<wfw:commentRss>http://www.arnab-deka.com/posts/2009/07/ruby-dup-vs-clone/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Ruby private class method</title>
		<link>http://www.arnab-deka.com/posts/2008/07/ruby-private-class-method/</link>
		<comments>http://www.arnab-deka.com/posts/2008/07/ruby-private-class-method/#comments</comments>
		<pubDate>Sat, 19 Jul 2008 01:37:00 +0000</pubDate>
		<dc:creator>Arnab</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.arnab-deka.com/posts/2008/07/ruby-private-class-method/</guid>
		<description><![CDATA[The following is just so I can remember it&#8230; You need not read all this. In Java, if you need a class whose constructor is private &#8211; so you can’t instantiate it from anywhere else, you&#8217;d do: public class AClass { private int a; private AClass(int a){ super(); this.a = a; } In Ruby, it&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>The following is just so I can remember it&#8230; You need not read all this.</p></blockquote>
<p>In Java, if you need a class whose constructor is private &#8211; so you can’t instantiate it from anywhere else, you&#8217;d do:</p>
<pre class="brush: java">
public class AClass {
  private int a;
  private AClass(int a){
    super();
    this.a = a;
  }
</pre>
<p>In Ruby, it&#8217;s a bit different. The why will come later (dynamic language), but just hiding the initialize method is not enough. You can still create an object coz you are actually calling the new method:</p>
<pre class="brush: ruby">
irb(main):001:0&gt; class AClass
irb(main):002:1&gt;   attr_reader :a
irb(main):003:1&gt;   private
irb(main):004:1&gt;   def initialize(a)
irb(main):005:2&gt;     @a = a
irb(main):006:2&gt;     end
irb(main):007:1&gt;   def some_other_method
irb(main):008:2&gt;     &quot;ha&quot;
irb(main):009:2&gt;     end
irb(main):010:1&gt;   end
=&gt; nil
irb(main):011:0&gt; obj = AClass.new(100)
=&gt; #&lt;aclass :0xb75768c4 @a=100&gt;
irb(main):012:0&gt; obj.a
=&gt; 100
irb(main):013:0&gt; obj.some_other_method
NoMethodError: private method `some_other_method&#039; called for #&lt;/aclass&gt;&lt;aclass :0xb75768c4 @a=100&gt;
        from (irb):13
        from :0
irb(main):014:0&gt;
</pre>
<p>You&#8217;d have to hide the new method:</p>
<pre class="brush: ruby">
class AClass
  attr_reader :a
  def initialize(a)
    @a = a
  end
  def self.test
    &quot;test&quot;
  end
  private_class_method :test
end

puts AClass.test
</pre>
<p>That shows:</p>
<pre class="brush: ruby">
test.rb:12: private method `test&#039; called for AClass:Class (NoMethodError)
</pre>
<p></aclass></p>
]]></content:encoded>
			<wfw:commentRss>http://www.arnab-deka.com/posts/2008/07/ruby-private-class-method/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

