<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Plough => Ruby]]></title>
  <link href="Plough => Ruby/atom.xml&#8221; rel=&#8221;self&#8221;/>
  <link href="Plough => Ruby/&#8221;/>
  <updated>2011-12-04T23:15:59+00:00</updated>
  <id>Plough => Ruby/</id>
  <author>
    <name><![CDATA[andHapp]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Installing any Ruby source on your local machine with RVM]]></title>
    <link href="Plough => Ruby/2011/12/04/installing-any-ruby-source-on-your-local-machine-with-rvm.html/&#8221;/>
    <updated>2011-12-04T00:00:00+00:00</updated>
    <id>Plough => Ruby/2011/12/04/installing-any-ruby-source-on-your-local-machine-with-rvm</id>
    <content type="html"><![CDATA[<p>Now, if you are like me you probably have ruby source checked out on your machine to ensure that you stay informed with the newest features and ponder through the ruby source at will. I started wondering what if I want to install the ruby from the source and test my gems out and test it against well-known libraries to see how they fare. Firstly, I thought of doing the ./configure -> make -> make install dance but then I realised&#8230;yes you&#8217;re absolutely right, why not use <a href="https://github.com/wayneeseguin/rvm">RVM</a>.</p>

<p>What RVM? I must be out of mind.</p>

<p>But, hey, RVM downloads ruby source code and installs it on your machine. The only difference is that I have got the ruby source checked-out on my machine and I want to use that as the source. And yes, RVM is awesome. I have spoken to <a href="https://github.com/wayneeseguin">Wayne</a> (via IRC) and the man is an absolute genius, very polite and helpful.</p>

<p>So, somehow, I need to accomplish the following:</p>

<ul>
<li>Hey RVM, don&#8217;t download the ruby source.</li>
<li>Here&#8217;s the location of the ruby source, use that and install it.</li>
<li>Voila!</li>
</ul>


<p>But, how do I do that? I started looking at RVM source code and I am not an expert at bash scripting, so I figured why not just mail RVM mailing list. I got the following helpful response from <a href="https://github.com/mpapis">Micheal Papis</a>.</p>

<pre>
it's not yet supported to use sources/rubies provided by user, but it
will be in rvm 2.0

as for using it now, you could use $rvm_path/src - and provide your
sources there ... not sure how it will work, you have to experiment a
bit
</pre>


<p>That clue was enough for me and like he said, I experimented a little bit. When you run something like:</p>

<pre>
rvm install ruby-1.9.2
</pre>


<p>RVM downloads the source code into $rvm_path/repos, moves it over to $rvm_path/src and then does the configure, compile dance. I created a symlink in $rvm_path/repos pointing at the local ruby git repository on my machine. And, then I ran the install command. Here&#8217;s the output I get:</p>

<pre>
~/.rvm/src$ rvm install ruby-head
Installing Ruby from source to: /Users/andhapp/.rvm/rubies/ruby-head, this may take a while depending on your cpu(s)...

ruby-head - #fetching 
HEAD is now at 02035ba Merge branch 'trunk' of git://github.com/ruby/ruby into trunk

From github.com:andhapp/ruby
 * branch            trunk      -> FETCH_HEAD
Already up-to-date.
Copying from repo to src path...
ruby-head - #configuring 
ruby-head - #compiling 
ruby-head - #installing 
Retrieving rubygems-1.8.10
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  243k  100  243k    0     0   456k      0 --:--:-- --:--:-- --:--:--  540k

Extracting rubygems-1.8.10 ...
Removing old Rubygems files...
-e:1: Use RbConfig instead of obsolete and deprecated Config.
Installing rubygems-1.8.10 for ruby-head ...
Installation of rubygems completed successfully.
ruby-head - adjusting #shebangs for (gem irb erb ri rdoc testrb rake).
ruby-head - #importing default gemsets (/Users/andhapp/.rvm/gemsets/)
Install of ruby-head - #complete 

</pre>


<p>This line &#8216;HEAD is now at 02035ba Merge branch &#8216;trunk&#8217; of git://github.com/ruby/ruby into trunk&#8217; is the last commit message on my local ruby git repository.</p>

<p>This line &#8216;From github.com:andhapp/ruby&#8217; reflects the fact that rvm is using my git repository and not ruby&#8217;s repository and updating the local source to the latest before installing.</p>

<p>I decided to call the ruby installation ruby-head. You can call it anything you fancy.</p>

<p>Here&#8217;s the version on my machine now:</p>

<pre>
~/.rvm/src$ rvm use ruby-head
Using /Users/andhapp/.rvm/gems/ruby-head
~/.rvm/src$ ruby -v
ruby 2.0.0dev (2011-12-03 trunk 33936) [x86_64-darwin10.8.0]
</pre>


<p>Awesome!</p>

<p>PS: I am sure there are other details about RVM&#8217;s installation procedure that I have missed out and Wayne or Micheal will be kind enough to enlighten me.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Inconsistent hashes]]></title>
    <link href="Plough => Ruby/2011/04/21/inconsistent-hashes.html/&#8221;/>
    <updated>2011-04-21T00:00:00+00:00</updated>
    <id>Plough => Ruby/2011/04/21/inconsistent-hashes</id>
    <content type="html"><![CDATA[<p>To clarify, hashes here does not mean the Hash class. Object&#8217;s in ruby have a hash method that returns a hash code for an object. The hash is also used in the background by the eql? method. So, it&#8217;s safe to say that two objects are equal if their hash methods return the same value.</p>

<p>Now, carry out a simple exercise and see what happens. Fire up an IRB session and run the following code, one by one:</p>

<pre>
    "test".hash
    1.hash
    [].hash
</pre>


<p>And note the output after every command run. Now, exit out of IRB and start a fresh session and run the same piece of code again. This time you will see the hash values have changed completely. This might be a bit surprising but it has been implemented in Ruby 1.9 for security reasons as it avoids one from guessing hash values. I picked this up from Ruby-core ML discussion and hope you find it useful.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[An Interesting Ruby Method]]></title>
    <link href="Plough => Ruby/2011/04/17/an-interesting-ruby-method.html/&#8221;/>
    <updated>2011-04-17T00:00:00+00:00</updated>
    <id>Plough => Ruby/2011/04/17/an-interesting-ruby-method</id>
    <content type="html"><![CDATA[<p>In this post, I will talk about a ruby method that I had no idea existed which might come handy in debugging your code.</p>

<p>The method I am talking about is <em>set_trace_func</em>. It&#8217;s part of the Kernel class and it does what it says. Allows one to set the method tracing on a method. The following snippet explains it further. Here, we have a class, TestingSetProcFunc:</p>

<pre>
    class TestingSetProcFunc
      def traceThisMethod
        source = 1
        target = 2
      end
    end
</pre>


<p>To inject set_trace_func in, it needs to be called before the method is invoked, like this:</p>

<pre>    
    puts "Event    File:Line                Id          Binding        Classname"
    set_trace_func proc { |event, file, line, id, binding, classname|
      printf "%8s %s:%-2d %20s %12s %8s\n", event, file, line, id, binding, classname
    }
</pre>


<p>It takes a proc with upto 6 arguments. These are the events with their brief descriptions:</p>

<ul>
<li>c-call (call a C-language routine)</li>
<li>c-return (return from a C-language routine)</li>
<li>call (call a Ruby method)</li>
<li>class (start a class or module definition)</li>
<li>end (finish a class or module definition)</li>
<li>line (execute code on a new line)</li>
<li>raise (raise an exception)</li>
<li>return (return from a Ruby method).</li>
</ul>


<p>Now, to run this we just need to call the method and look at the output:</p>

<pre>
    tracer = TestingSetProcFunc.new
    tracer.traceThisMethod
</pre>


<p>This is what the output will look like when you run it on the command line:</p>

<pre>    
Event    File:Line                Id          Binding        Classname
c-return test.rb:11       set_trace_func #<Binding:0x0b53c4>   Kernel
    line test.rb:13                      #<Binding:0x0b52fc>         
  c-call test.rb:13                  new #<Binding:0x0b525c>    Class
  c-call test.rb:13           initialize #<Binding:0x0b5144> BasicObject
c-return test.rb:13           initialize #<Binding:0x0b5090> BasicObject
c-return test.rb:13                  new #<Binding:0x0b4ff0>    Class
    line test.rb:14                      #<Binding:0x0b4f50>         
    call test.rb:2       traceThisMethod #<Binding:0x0b4eb0> TestingSetProcFunc
    line test.rb:3       traceThisMethod #<Binding:0x0b4dfc> TestingSetProcFunc
    line test.rb:4       traceThisMethod #<Binding:0x0b4d5c> TestingSetProcFunc
  return test.rb:5       traceThisMethod #<Binding:0x0b4cbc> TestingSetProcFunc    
</pre>


<p>This output gives one a good idea about the work that is happening in the background. The weird looking Binding instance is the context at that particular place in the code. I have just scratched the surface and I am sure there&#8217;s a lot one can do with this method. Have a look at the <a href="https://github.com/ruby/ruby/blob/trunk/test/ruby/test_settracefunc.rb">ruby&#8217;s test for set_trace_func</a> for more useful ways of employing it.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Ruby Hacking Guide - Chapter 1]]></title>
    <link href="Plough => Ruby/2011/03/12/ruby-hacking-guide-chapter-1.html/&#8221;/>
    <updated>2011-03-12T00:00:00+00:00</updated>
    <id>Plough => Ruby/2011/03/12/ruby-hacking-guide-chapter-1</id>
    <content type="html"><![CDATA[<p>I have completed proof-reading and testing the code from old Ruby Hacking Guide and re-releases in the wild again. It still needs some styling work but I will hopefully find time to sort that out this week.</p>

<p>In the meantime, have a <a href="http://rubyhacking.andhapp.co.uk/2011/01/30/chapter-1.html">read through</a> and see if you spot any mistakes.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Free Ruby 1.9 Online Book]]></title>
    <link href="Plough => Ruby/2011/03/12/free-ruby-1.9-online-book.html/&#8221;/>
    <updated>2011-03-12T00:00:00+00:00</updated>
    <id>Plough => Ruby/2011/03/12/free-ruby-1.9-online-book</id>
    <content type="html"><![CDATA[<p>Just found this nicely done online book on <a href="http://ruby.runpaint.org/">Ruby 1.9</a>, in particular. It&#8217;s a must see.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Ruby File append mode]]></title>
    <link href="Plough => Ruby/2011/01/21/ruby-file-append-mode.html/&#8221;/>
    <updated>2011-01-21T00:00:00+00:00</updated>
    <id>Plough => Ruby/2011/01/21/ruby-file-append-mode</id>
    <content type="html"><![CDATA[<p>There are different file modes available to the developer when creating and opening new files in Ruby. One that I didn&#8217;t know about was &#8220;a&#8221; which basically means append to the end of the file rather than starting a new one. What could it be useful for? One example would be as a log file of some sort where one wants to preserve the old data and add new data to the end of the file. Very trivial but helpful if you know about these things. Just makes you a better developer.</p>

<p>A simple code example would be:</p>

<pre>
    file = File.new("datamapper.log", "a")  
</pre>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Ruby Hacking Guide]]></title>
    <link href="Plough => Ruby/2011/01/17/ruby-hacking-guide.html/&#8221;/>
    <updated>2011-01-17T00:00:00+00:00</updated>
    <id>Plough => Ruby/2011/01/17/ruby-hacking-guide</id>
    <content type="html"><![CDATA[<p>I got hold of an out-of-date <a href="http://hawthorne-press.com/WebPage_RHG.html">Ruby Hacking Guide</a> and it looks very interesting. Therefore, in order to improve my understanding of Ruby internals, I have decided to spend time in reading it and the writing posts about it. The entire book can be downloaded in the form of HTML pages and might not make sense since some of it has been machine translated.</p>

<p>I hope my efforts are useful for anyone willing to venture into Ruby Internals.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Method default arguments and passing nil value]]></title>
    <link href="Plough => Ruby/2011/01/03/method-default-arguments-and-passing-nil-value.html/&#8221;/>
    <updated>2011-01-03T00:00:00+00:00</updated>
    <id>Plough => Ruby/2011/01/03/method-default-arguments-and-passing-nil-value</id>
    <content type="html"><![CDATA[<p>This is something very trivial and I kind of observed it whilst programming couple of weeks ago. For example, you had a method like this:</p>

<pre>
  class SomeClass
    def some_method(some_argument = '')
      raise ArgumentError unless some_argument
    end
  end
</pre>


<p>Now, I was under the impression that if I passed in a nil into this method, for some reason some_argument will still have the default value(&#8221;) as opposed to the nil value passed in but default arguments come into play when no value is passed in for the method arguments. But I was passing in nil which is an instance of NilClass and therefore some_argument gets assigned the nil value and an exception is raised.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Convert Array to Hash mystery]]></title>
    <link href="Plough => Ruby/2011/01/03/convert-array-to-hash-mystery.html/&#8221;/>
    <updated>2011-01-03T00:00:00+00:00</updated>
    <id>Plough => Ruby/2011/01/03/convert-array-to-hash-mystery</id>
    <content type="html"><![CDATA[<p>It is always easy to find solutions on Google but the real fun is in finding out how a bit of code works. It just helps you understand much more about the language and how it behaves. Converting an array to hash is easy. Just use this piece of code that I found on google:</p>

<pre>
  some_array = [1,2,3]
  some_hash = Hash[*(some_array.collect{|v| [v,v]}.flatten)] # yields {1=>1, 2=>2, 3=>3}
</pre>


<p>Few people have asked the question behind this conversion and I just decided to break it apart and tackle it bit by bit. Our objective, again, is to convert an array to a hash. Hash&#8217;s ruby documenation tells us that a new Hash object can be created by using even number of arguments. Something similar to the following code:</p>

<pre>
  some_hash = Hash[1,1,2,2,3,3] # This creates a hash object similar to this {1=>1, 2=>2, 3=>3}
</pre>


<p>All we need to do now is convert our some_array (defined in the first code snippet) and convert it into [1,1,2,2,3,3].</p>

<p>It&#8217;s simple really. We take the some_array and convert it into an array&#8217;s or array like this:</p>

<pre>
  some_array = [1,2,3]
  some_array.collect{|v| [v, v]} # will yield [[1,1], [2,2], [3,3]]
</pre>


<p>Now to convert it into [1,1,2,2,3,3] we just need to flatten this array of arrays like this:</p>

<pre>
  some_array = [1,2,3]
  some_array.collect{|v| [v, v]}.flatten # will yield [1,1,2,2,3,3]
</pre>


<p>Now, all we need to do is use the splat (*) unary operator. The splat operator expands the supplied array into individual arguments which is what we need to convert array into a hash. You could also achieve the same with the following snippet:</p>

<pre>
  some_array = [1,2,3]
  some_hash = Hash[*(some_array+some_array).sort] # yields {1=>1, 2=>2, 3=>3}
</pre>


<p>I hope you can work that out yourself. I hope this little discussion helped you.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Paperclip and rescue]]></title>
    <link href="Plough => Ruby/2010/07/06/paperclip-and-rescue.html/&#8221;/>
    <updated>2010-07-06T00:00:00+00:00</updated>
    <id>Plough => Ruby/2010/07/06/paperclip-and-rescue</id>
    <content type="html"><![CDATA[<p>Reading Open Source Code is probably the best way of learning new ways. Paperclip is an amazing file upload tool by brilliant guys at Thoughtbot. And yesterday, while going through their code I realised that <strong>rescue</strong> can be used as a statement modifier. For example, consider this block of code below:</p>

<pre>
  type = (self.path.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase
</pre>


<p>What do you think happens here?
Its quite simple really. If the first statement (the match bit) raises and exception the second statement is executed instead.</p>

<p>Another way to write this would be:</p>

<pre>
  begin
    type = (self.path.match(/\.(\w+)$/)[1]).downcase
  rescue
    "octet-stream"
  end
</pre>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Install pg and mysql gems]]></title>
    <link href="Plough => Ruby/2010/02/22/install-pg-and-mysql-gems.html/&#8221;/>
    <updated>2010-02-22T00:00:00+00:00</updated>
    <id>Plough => Ruby/2010/02/22/install-pg-and-mysql-gems</id>
    <content type="html"><![CDATA[<p>This is not entirely realted to ruby but if you ever program with ruby you will find yourself using pg and mysql gems and the issue is how exactly do I install them. This mini-post (rather tumble) is just to make a note of this. Run the following in Teerminal.</p>

<p>PostgreSql</p>

<pre>
  export PATH=/usr/local/pgsql/bin:${PATH}
  gem install pg
</pre>


<p>MySql</p>

<pre>
  export PATH=/usr/local/mysql/bin:${PATH}
  gem install mysql
</pre>


<p>Also, please note that you should have postgres and mysql installed on your machine.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Proc, proc, blocks]]></title>
    <link href="Plough => Ruby/2009/12/20/proc-proc-blocks.html/&#8221;/>
    <updated>2009-12-20T00:00:00+00:00</updated>
    <id>Plough => Ruby/2009/12/20/proc-proc-blocks</id>
    <content type="html"><![CDATA[<p>I know you must be thinking proc and Proc is the same thing and I must have mistyped. But, proc and Proc are different things. Blocks is a beautiful concept and you can achieve so much by using blocks carefully that it is unbelievable. I created a simple DSL using blocks and Faker gem to spit out XML used for testing purposes. I mean it took me few hours to do the first version up and running in Sinatra. Amazing.</p>

<p>So, block is nothing more than bits of code within curly brackets. The concept of blocks is used excessively throughout Ruby in iterators like inject, select, map, each and so on and so forth. For example:</p>

<pre>
def example_from_a_block
  puts "Should call a block"
  yield 
  puts "Yes, I did!"
end
</pre>


<p>and invoke it like:</p>

<pre>
example_from_a_block { puts "in a block" }
</pre>


<p>But blocks do have problems. Not exactly problems, but yeah shortcoming for sure. They are not objects. So&#8230;what difference does it make if they are not objects. I don&#8217;t care man. I like them. Exactly you like blocks but you would love blocks wrapped as objects. Yes, these things do exist. They are called proc or lambda. So what is a proc then? It is basically a block but with object like features, I mean you can manipulate them and pass them around like regular objects. Cool.</p>

<p>To create a proc, just do:</p>

<pre>
p = Proc.new { puts "I am a proc" }
</pre>


<p></p>

<p>It is absolutely essential to pass a block to a proc. &#8220;p&#8221; is basically an instance of the class <a href="http://ruby-doc.org/core/classes/Proc.html">Proc</a>. Run this in you irb session and confim that it is indeed an object with an object_id:</p>

<pre>
p.object_id
</pre>


<p>Hmm&#8230;two down one to go. What exactly is a proc then. proc is just a simple global method, if you will, of the Kernel module. So, you can just invoke it like this:</p>

<pre>
kernels_proc_variable = proc {|a| a + 10 }
</pre>


<p>Now, proc behaves differently in Ruby 1.8 and Ruby 1.9. In 1.8, it returns a lambda where as in 1.9 it is a synonym for Proc.new. So, please be aware of this simple yet pivotal difference. Pivotal because lambda&#8217;s and proc&#8217;s are slightly different, although on the surface they look the same. They are both instances of Proc so let us just say they are siblings. There is so much more you can do with Procs and this post has just touched the surface of it. I will discuss lambda and closures in the coming posts and then compare them.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Ruby streams - $stdin, $stdout and $stderr]]></title>
    <link href="Plough => Ruby/2009/11/19/ruby-streams-stdin-stdout-and-stderr.html/&#8221;/>
    <updated>2009-11-19T00:00:00+00:00</updated>
    <id>Plough => Ruby/2009/11/19/ruby-streams-stdin-stdout-and-stderr</id>
    <content type="html"><![CDATA[<p>It is obvious from the subject that I am going to talk about the streams $stdin, $stdout and $stderr but it would be a fun ride with lots of examples and good explanations. However, there is another set of global variables called STDOUT, STDIN, STDERR. In addition to STDIN, there is ARGF and DATA for reading data in so you know you can research into these things.</p>

<p>Any variable in ruby that starts with a $ sign is a global variable. You do not need to define it. It is given to you. Great!. Now, every ruby process on a UNIX (POSIX) system gives you three file descriptors stdin(fd0), stdout(fd1) and stderr(fd2). To generalise, every process is presumed to have three file descriptors, namely, standard output, standard input and standard error to communicate to the underlying OS. Since, ruby runs as a process it would also get these three file descriptors. So, $stderr, $stdout and $stdin are basically wrappers to those file descriptors and assist us in talking to the OS. Trivial operations like print this out on the console actually employs $stdout for outputting.</p>

<p>What kind of objects are they? Let us go to good old irb and run some code. Run the code below:</p>

<pre>
$stdout.kind_of?(IO)
</pre>


<p>This would give you &#8220;true&#8221; which bascially means that $stdout is an IO object. <a href="http://ruby-doc.org/core/classes/IO.html#M002278">IO</a> is the main input output library in ruby. Do check out the rdoc for other exciting things you can do with it. Ok. Good that we have these file descriptors so what. I do not need to know how &#8220;puts&#8221; outputs stuff to the console. I just use it. Well, that is good but one should definitely have a good understanding of controlling where the output goes otherwise when someone asks you - <strong>&#8220;How do I redirect my output to a file instead of console?&#8221;</strong>, you would just sit there with no answer. So, let us try and find an answer to the same question so that you do not look like a fool.</p>

<p>As it happens, we can actually redefine the $stdout. The following code would do exactly that when run in irb:</p>

<pre>
$stdout = File.open("test.log", "w")
</pre>


<p>It basically tells $stdout to spit everything out to a file called &#8220;test.log&#8221;. That&#8217;s it. Its done. Now, when you send a mesage to puts method it would use the newly defined $stdout and do the needful. Run this code in the same irb session as above and and see what happens:</p>

<pre>
puts "I am going to the file. It is more fun than printing on the cosole."
</pre>


<p>and you would not see this printed out in the console. Go and check the file test.log but to your surprise it would not be there. So, where the heck is it? Well, what happens is it is stored in a buffer and not written to the file until the buffer gets full (I am not entirely sure about this but I am guessing that would be the case). Now, if you terminate your irb session and check test.log you would find the entire ouput there but I do not want to end the session. I want to do the work and at the same time check the output. Well, not to worry the flush method does exactly that. Run this after every puts or print:</p>

<pre>
$stdout.flush
</pre>


<p>Voila! This clears the buffer and writes everthing to the file. So, there you are now you know how to redirect the output to a file. But hang on what if I want to go back to the console in the same session. Is that possible? Ofcourse, that is possible. Remember I told you about STDOUT at the beginning well that comes to the rescue. STDOUT and $stdout point to the same IO object. You can check that by running the following code in irb:</p>

<pre>
$stdout.equal?(STDOUT) 
</pre>


<p>and this gives you true, which proves my point. So, in order to go back to the original state you can just do this in order to redefine $stdout:</p>

<pre>
$stdout = STDOUT
</pre>


<p></p>

<p>Simple! Now, when you do:</p>

<pre>
puts "Oh Em Gee, I am back on the console."
</pre>


<p></p>

<p>You will see it straight away on your console. BTW, instead of $stdout you can redefine STDOUT and redirect the output to a file but puts or print would not be bothered about it as they use $stdout which is still pointing to the console.</p>

<p>Now comes the most interesting bit of the whole post. Are system calles affected by the redefining of $stdout. You know system calls. Well, in ruby you can use a system method to call the underlying OS functions, for example:</p>

<pre>
system('ls -l')
system('echo Wheeee')
</pre>


<p>So, the question is what happens when you redefine the $stdout does that affect the output of these system calls. And the answer is Nope, it does not. The child processes like system would still use the existing output channel that the ruby process had in the beginning. Redefining, $stdout would not change the file descriptor. The file descriptors are still there and when we redefine $stdout we just stop using them. But the native calls to the OS will still use the console for output.</p>

<p>That was a long post! I hope now you are better equipped with the IO knowledge and how it all works in ruby.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Serendipity]]></title>
    <link href="Plough => Ruby/2009/11/04/serendipity.html/&#8221;/>
    <updated>2009-11-04T00:00:00+00:00</updated>
    <id>Plough => Ruby/2009/11/04/serendipity</id>
    <content type="html"><![CDATA[<p>I accidently found a nifty way of calling <del datetime="2009-11-04T09:19:06+00:00">class</del> singleton methods. Imagine you have this code:</p>

<pre>

class FoundANewWay
    def self.to_call_a_singleton_method
        puts "It works!"
    end
end
</pre>


<p>and you can call it like this:</p>

<pre>
FoundANewWay.to_call_a_singleton_method

or

FoundANewWay::to_call_a_singleton_method
</pre>


<p>Cool!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Immediate Values]]></title>
    <link href="Plough => Ruby/2009/10/31/immediate-values.html/&#8221;/>
    <updated>2009-10-31T00:00:00+00:00</updated>
    <id>Plough => Ruby/2009/10/31/immediate-values</id>
    <content type="html"><![CDATA[<p>In a <a href="http://www.ploughthroughruby.co.uk/2009/08/is-variable-an-object/">previous post</a>, I have explained that variables are basically passed by values in ruby but since they have a reference to the original object any mutator methods can bascially modify the object itself. However, there are two exceptions to this; Fixnum and Symbol.</p>

<p>Both, Fixnum and Symbol, store the values and have no reference to the object. This also applies that there are no mutator methods for Fixnum and Symbol and they are immutable. So, how can we actually prove this fact. Let us do a simple experiment and I think I might have done this before but I do not want you going back and forth between posts so let us just do it again. Run the code snippet and we are going through each step:</p>

<pre>
  fixnum_1 = 3
  p fixnum_1.object_id
  fixnum_2 = 3
  p fixnum_2.object_id
  str_1 = "3"
  p str_1.object_id
  str_2 = "3"
  p str_2.object_id
</pre>


<p>You will see that both the fixnum variables have the same object_id where as with str variables they will be different. So, what does that mean? It simply means that two fixnums of same value always represent the same object instance, so instance variables for Fixnum with value 1 are shared across the system. The same is the case with Symbol.</p>

<p>Ok. Fine. This makes perfect sense but why should I bother with all this explanation. Well, that is a million dollar question really and the answer to that is &#8220;You can&#8217;t define singleton methods on Fixnums and Symbols&#8221;. What? Why? I know this is confusing but when in doubt think of an example.</p>

<p>We previously established that all the fixnum variables with same value are actually pointing to the same object instance. If let us say I want to define a singleton method on one then it would really define the singleton method on that object instance which means all the fixnum variables with same value would really share that new method you have added. Therefore, in order to cut that possibilty out one cannot define singleton methods on Fixnum, and Symbls.</p>

<p>Update: I have just realised that true (TrueClass), false (FalseClass) and nil (NilClass) also store the references as immediate values. And, yes there is a TrueClass, FalseClass and NilClass and true, false and nil are singleton instances of these classes.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Class names are constants ]]></title>
    <link href="Plough => Ruby/2009/10/31/class-names-are-constants.html/&#8221;/>
    <updated>2009-10-31T00:00:00+00:00</updated>
    <id>Plough => Ruby/2009/10/31/class-names-are-constants</id>
    <content type="html"><![CDATA[<p>Ruby is an object oriented programming. Let us look at a code sinpet:</p>

<pre>
 str =  String.new("ruby rocks")
</pre>


<p>So, we define a variable called &#8220;str&#8221;, which stores a pointer to the object created by sending &#8220;new&#8221; on &#8220;String&#8221;. Here, &#8220;String&#8221; receives the &#8220;new&#8221; message but for &#8220;String&#8221; to take any action when it receives &#8220;new&#8221; message it must have a reference to the object called String. Therefore, there must be a corresponding constant to every class in ruby. It can&#8217;t be a variable as it starts with an uppercase.</p>

<p>Actually, that is exactly what happens. Every class in ruby has a global constant which stores a reference to the object and is used for method invocations. So, there are two things really one is the constant named String and the other is the object named String.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Ruby object model]]></title>
    <link href="Plough => Ruby/2009/10/09/ruby-object-model.html/&#8221;/>
    <updated>2009-10-09T00:00:00+00:00</updated>
    <id>Plough => Ruby/2009/10/09/ruby-object-model</id>
    <content type="html"><![CDATA[<p>Right, so you know Ruby&#8217;s object model. Well here&#8217;s a little code snippet by JRuby creator Ola Bini and it drives the point home really.</p>

<pre>
class Obj
  def something
    puts "calling simple"
    @abc = 3*42
    def something
      puts "calling memoized"
      @abc
    end
    something
  end
end

o = Obj.new
o.something
o.something
o.something

</pre>


<p>The output of the code is:</p>

<pre>
calling simple
calling memoized
calling memoized
calling memoized
</pre>


<p>Let us look at the code and anaylise it. &#8216;o&#8217; is an instance of &#8216;Obj&#8217; class. &#8216;something&#8217; is an instance method of &#8216;O&#8217;, therefore it can access it. The first &#8216;o.something&#8217; would call the instance method defined in &#8216;Obj&#8217; class. So, it prints &#8220;calling simple&#8221; and then the second &#8216;something&#8217; defines a method on instance &#8216;o&#8217; because inside the first &#8216;something&#8217; self is same as instance &#8216;o&#8217;.</p>

<p>Now, what do you get when you do something like this:</p>

<pre>
def o.something
     puts "I am o's singleton method."
end
</pre>


<p>Yes, you get a singleton method on the instance. In this case, that&#8217;s exactly what happens. The second &#8216;something&#8217; defines a singleton method on instance &#8216;o&#8217;.  We are still in the middle of executing the first something. The last line of the first something (or the outer something) calls the method &#8216;something&#8217;. What the hell? Cyclic messaging!!!! Never ending loop. Yeah, but the code runs and exits gracefully.</p>

<p>Well, the call to &#8216;something&#8217; would actually go and look for &#8216;something&#8217; method and before it finds a &#8216;something&#8217; method defined in the class &#8216;Obj&#8217; it would find the singleton-method &#8216;something&#8217; and execute that. So, what would that print. Yeah, you are right it prints &#8220;calling memoized&#8221;. The second and third calls to something will again encounter the &#8216;something&#8217; singleton method and execute that and it would not bother to go and look for the something defined as an instance method in class &#8216;Obj&#8217;.</p>

<p>I know you are confused. Why would it go and look for the singleton method and not the instance method. This is the magic behind Ruby&#8217;s object model. Please head over to Ola Bini&#8217;s blog and read the article on <a href="http://ola-bini.blogspot.com/search/label/metaprogramming">metaprogramming</a>. He goes into a lot more detail.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[define_method, instance_eval and class_eval]]></title>
    <link href="Plough => Ruby/2009/09/30/define_method-instance_eval-and-class_eval.html/&#8221;/>
    <updated>2009-09-30T00:00:00+00:00</updated>
    <id>Plough => Ruby/2009/09/30/define_method-instance_eval-and-class_eval</id>
    <content type="html"><![CDATA[<p>Right, so this is a tad confusing and the reason I am explaining is to ensure that I understand it properly.</p>

<p><strong>instance_eval</strong> - It creates singleton methods on the object it is invoked on. If it is invoked on a Class object then these methods become singleton methods of the class. Some people would call them <del datetime="2009-09-30T19:13:53+00:00">&#8220;class methods&#8221;</del> but these are simply methods in an object&#8217;s singleton class. Here&#8217;s the code:</p>

<pre>
SomeObject.instance_eval (def singleton_method; "singleton_method";end)
</pre>


<p><strong>class_eval</strong> - It creates an instance method on the object. Simple there is nothing confusing about this. Here&#8217;s an example:</p>

<pre>
SomeObject.class_eval(def instance_method;"instance_method";end)
</pre>


<p>Now, define method when used inside either class_eval or instance_eval s immune to the usual behaviour.</p>

<p>Why, you may ask?</p>

<p>Because the documentation says so. As per the documentation &#8220;define method - Defines an instance method in the receiver&#8221;. Therefore, it does not matter if you use define_method inside class_eval or instance_eval it would always create an instance method. Now, the question to ask is - &#8220;Is there no way to define a singleton method using defne_method?&#8221;. Well, I still need to investigate that. It would probably be in an update to this post. Hope it all makes sense. Ruby metaprogramming is awesome only if you know what you are doing and to get to that stage one needs to spend countless hours metaprogramming.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Ruby online courses]]></title>
    <link href="Plough => Ruby/2009/09/24/ruby-online-courses.html/&#8221;/>
    <updated>2009-09-24T00:00:00+00:00</updated>
    <id>Plough => Ruby/2009/09/24/ruby-online-courses</id>
    <content type="html"><![CDATA[<p>Anyone interested in learning ruby then head over to <a href="http://www.rubylearning.org">RubyLearning</a> blog with plethora of online courses. Some of them are free and some charge a very nominal price. I am currently scheduled to take Ruby Shoes course but there are others like: Ruby Core, ruby metaprogramming. I am enrolled and currently studying the ruby meta-programming course and it is fabulous. I paid $5 for it but it is compared to what you will achieve by the time you get to the other side. So, do not delay any further.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Ruby idioms]]></title>
    <link href="Plough => Ruby/2009/09/24/ruby-idioms.html/&#8221;/>
    <updated>2009-09-24T00:00:00+00:00</updated>
    <id>Plough => Ruby/2009/09/24/ruby-idioms</id>
    <content type="html"><![CDATA[<p>You can write a complete ruby script as a string and run it. Ruby (rather MRI) would just evalutae the string by executing it. For example:</p>

<pre>
"#{def x(s); puts(s.reverse); end; ('1'..'3').each{|aStr| x(aStr)} }"
</pre>


<p>This is absolutely valid.</p>
]]></content>
  </entry>
  
</feed>

