<?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>Nine Mohs &#187; Ruby</title>
	<atom:link href="http://code.scrapcrap.org/tag/ruby/feed" rel="self" type="application/rss+xml" />
	<link>http://code.scrapcrap.org</link>
	<description>Ruby, Programming, Technology, Fun</description>
	<lastBuildDate>Sun, 07 Feb 2010 11:19:20 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Design Patterns in Ruby : The Factory Method</title>
		<link>http://code.scrapcrap.org/dpr2</link>
		<comments>http://code.scrapcrap.org/dpr2#comments</comments>
		<pubDate>Sun, 26 Apr 2009 17:47:09 +0000</pubDate>
		<dc:creator>kitallis</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Creational]]></category>
		<category><![CDATA[Factory Method]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Russ Olsen]]></category>

		<guid isPermaLink="false">http://code.scrapcrap.org/?p=291</guid>
		<description><![CDATA[This is an article series on implementing programming Design Patterns in Ruby. This is the second part of the series and here&#8217;s a link to the last article on the Template Design Pattern.
The Factory Method Pattern
I have to this say this, but Wikipedia has a pretty good explanation and a Ruby implementation for this Creational [...]]]></description>
			<content:encoded><![CDATA[<p>This is an article series on implementing programming Design Patterns in Ruby. This is the second part of the series and here&#8217;s a <a href="http://code.scrapcrap.org/dpr1">link</a> to the last article on the Template Design Pattern.</p>
<h3>The Factory Method Pattern</h3>
<p>I have to this say this, but Wikipedia has a pretty good explanation and a Ruby implementation for this Creational Pattern, so I&#8217;d be focusing mainly upon the general idea of why this pattern is similar to the Template Method pattern and explain some of its defined variants.</p>
<p><strong>What is it? </strong></p>
<p><strong><span style="font-weight: normal;">It is a Creational design pattern : defining how created objects should be mechanised as per the pattern as chances are there might be design problems with bad object control.</span></strong></p>
<p><strong>When is it needed? </strong></p>
<p><strong><span style="font-weight: normal;">It&#8217;s all about picking the right class. It&#8217;s pretty much like the Template Method pattern. In the Template Method pattern there was a generic portion which was stored in a base class and the other fill-in-the blanks were controlled by the subclasses and the Template method drove certain methods so that they needn&#8217;t be explicitly called. Here, with the Factory Method those subclasses determine what objects to be created. So the Factory Method is for creating objects as Template Method was for driving an algorithm.</span></strong></p>
<p><strong>How is it done?</strong></p>
<p><strong><span style="font-weight: normal;">Here&#8217;s my dummy implementation for the Factory Method pattern.</span></strong></p>
<pre class="brush:ruby">module Factory
  def draw
     raise NotImplementedError, "You need to call this method, brotha"
  end
end

class Circle
 include Factory
 def draw
   # Clear Screen
   # Draw Circle
 end
end

class Square
 include Factory
   def draw
     # Clear Screen
     # Draw Square
   end
end

class Tetrahedron
  include Factory
  def draw
    # Clear Screen
    # Draw Square
  end
end

class RandomShape
  include Factory
    def draw
      # Clear Screen
      # Draw any shape apart from the above three
    end
end

class CreateShape
  def self.CallShapes(shape)
    case(shape)
      when "Circle"
        Circle.new
      when "Square"
        Square.new
      when "Tetrahedron"
        Tetrahedron.new
    else
      RandomShape.new
    end
  end
end</pre>
<p>More precisely, the Shape module is for defining the Draw method which raises a predefined NotImplementedError exception object. Circle, Square and Tetrahedron are the subclasses which call the Shape module and are called by the Factory Method &#8211; CallShapes for creating objects out of them to be selected as per the user call.</p>
<p>This pattern is used when a class (the<em>Creator</em>) does not know beforehand all the subclasses that it will create. Instead, each subclass (the <em>Concrete Creator</em>) is left with the responsibility of creating the actual object instances.<br />
The example shown here is specifically a Parametrized Factory Method, that takes in certain parameters from the user and creates objects accordingly.</p>
<p>Abstract Factory Method can pretty much be understood by this UML diagram</p>
<p><img class=" alignnone" title="Factory Method UML" src="http://img111.imageshack.us/img111/307/dpr2.jpg" alt="Factory Method UML" width="536" height="354" /></p>
<p>(Courtesy : Design patterns in Ruby )</p>
<p>The basic idea behind Abstract Factory Methods are to form a group of factories that are compatible with each other. According to the diagram, there are Two Factories encapsulated by one single Abstract factory and each concrete factory produces its set of compatible products. And that&#8217;s pretty much what Abstract Factory Methods are.</p>
<p>Taking an example from the Book, the ActiveRecord library uses a form of this kind of pattern.<br />
ActiveRecord has an adapter class for each different kind of database that it uses like MySQL, Oracle. To set up the connection the user name, password, and a string containing the name of the adapter that ActiveRecord uses is supplied. So we enter &#8216;mysql&#8217; if we want to talk to a MySQL database and so on. To accomplish this a Base class is present that has no adapter related code.<br />
But there are Subclasses that modifying the Base code, that is, each adapter adds a method that creates its specific type of connection to<br />
the Base class.</p>
<pre class="brush:ruby">class Base
# Lots of non-adapter-related code removed...
end

class Base
  def self.mysql_connection(config)
 # Create and return a new MySQL connection, using
 # the user name, password, etc. stored in the
 # config hash...
  end
end

class Base
  def self.oracle_connection(config)
 # Create a new Oracle connection...
  end
end</pre>
<p>If a structured object creation method like the Factory Method in a class is not implemented, we might end up creating methods for each new object we want to create.</p>
<p><strong>References</strong></p>
<p><span style="color: #000000; text-decoration: none;">[1] <a href="http://en.wikipedia.org/wiki/Factory_method_pattern">Wikipedia</a></span></p>
<p>[2] <a href="http://www.programmersheaven.com/2/Tutorial-Design-Patterns-Factory-method"><span style="text-decoration: none;">Programmers Heaven</span></a></p>
<p><strong> </strong></p>
]]></content:encoded>
			<wfw:commentRss>http://code.scrapcrap.org/dpr2/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Design Patterns in Ruby : The Template Method</title>
		<link>http://code.scrapcrap.org/dpr1</link>
		<comments>http://code.scrapcrap.org/dpr1#comments</comments>
		<pubDate>Sun, 08 Mar 2009 19:58:20 +0000</pubDate>
		<dc:creator>kitallis</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[ControlTier]]></category>
		<category><![CDATA[GoF]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Russ Olsen]]></category>
		<category><![CDATA[Template Method]]></category>

		<guid isPermaLink="false">http://code.scrapcrap.org/?p=231</guid>
		<description><![CDATA[Just before a month ago I was sweating out, playing away with my small little Ruby programs which were surely not pieces of code you&#8217;ll want to read and learn with. Now just after my fifteen day brawl with the Design Patterns, I find myself a totally revamped programmer.
This is my new article series which [...]]]></description>
			<content:encoded><![CDATA[<p>Just before a month ago I was sweating out, playing away with my small little Ruby programs which were surely not pieces of code you&#8217;ll want to read and learn with. Now just after my fifteen day brawl with the Design Patterns, I find myself a totally revamped programmer.<br />
This is my new article series which would cover a few of the popular programming Design Patterns in software engineering devised by the<a href="http://en.wikipedia.org/wiki/Gang_of_Four_(software)"> GoF</a>. I would be starting off with some basic Design Patterns and then move onto Ruby specific patterns based upon the book &#8220;<a href="http://www.amazon.com/Design-Patterns-Ruby-Addison-Wesley-Professional/dp/0321490452">Design Patterns In Ruby</a>&#8221; by Russ Olsen.</p>
<p><img class="alignnone" title="Design Patterns In Ruby" src="http://ecx.images-amazon.com/images/I/51NG5mF-SAL._SL500_AA240_.jpg" alt="" width="240" height="240" /></p>
<p>The Design Patterns that&#8217;ll be explained are :</p>
<p>1. The Template Method (explained here)<br />
2. <a href="http://code.scrapcrap.org/dpr2">The Factory Method</a></p>
<p>(They will be updated as the series expands)<br />
You can Subscribe to my Blog Feeds for constant updates on the articles or you can follow me on www.twitter.com/kitallis<br />
This is the base article for the series and you can always look back at this as an archive for others.</p>
<p>Prerequisites would be, a knowledge of Ruby&#8217;s Object Oriented features and a belief that this would actually help you get better.<br />
These articles would follow a simple pattern of explaining the design pattern, disadvantages without it and improving with it. If you don&#8217;t quite get what I&#8217;m talking about, you might want to take a look at this.</p>
<h3>The Template Method Pattern</h3>
<p><strong>When is it needed?</strong><br />
The Design patterns are a way of solving a problem in a particular way and is in no way related to reducing the complexity of the algorithm.<br />
The basic problem on which this DP is implemented upon is a varying piece of code mixed in with the part that remains static. So we would be separating the code that stays the same (probably the algorithm) with the piece of code that is dynamic (probably the processing data).</p>
<p><strong>How can we do it?</strong><br />
By separating and encapsulating the common entities into a subclass and the changing entities/behaviour into derived classes and thereby allowing the common behaviour to not repeat itself.<br />
More specifically, building an abstract base class with a skeletal method (template method) that&#8217;d control the part that needs to vary by making calls to the Abstract Method whose actual control is further provided by the subclasses.<br />
Even more strictly, this is an actual application of the Template Method Pattern in the <a href="http://open.controltier.org/manuals/3.1/platform.html">ControlTier</a> project which defines an application installation procedure<br />
(other details are unnecessary here)</p>
<p><img class="alignnone" title="ControlTier Template Method Implementation  " src="http://img9.imageshack.us/img9/1048/packageinstallpackage.png" alt="" width="393" height="288" /></p>
<p>(Courtesy : <a href="http://apps.sourceforge.net/mediawiki/controltier/index.php?title=Main_Page">ControlTier Wiki</a>)</p>
<p>The Template Methods residing in the Abstract class are &#8216;driving&#8217; certain Operations and the subclasses are actually implementing those Operations. So here, InstallPackage is the Template Method which defines all usable methods and zip is the concrete subclass which calls methods it requires.</p>
<p>So, the quick advantages we get are :</p>
<p>1. We can expand to more subclasses even if they require a varying algorithm for the methods defined</p>
<p>2. The algorithm is separated from the static definitions and initialisations</p>
<p>This is my dummy code for the pattern</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p231code4'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p2314"><td class="code" id="p231code4"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Package  <span style="color:#008000; font-style:italic;"># this is the abstract base class</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> InstallPackage  <span style="color:#008000; font-style:italic;"># this is the template method</span>
&nbsp;
  create
  installDependencies
  prepare
  get
  extract
  finish
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> installDependencies
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> prepare
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> get
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> extract
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> finish
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> Zip <span style="color:#006600; font-weight:bold;">&amp;</span>lt; Package  <span style="color:#008000; font-style:italic;"># this is the concrete subclass</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> create
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> extract
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>And it might be called this way</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p231code5'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p2315"><td class="code" id="p231code5"><pre class="ruby" style="font-family:monospace;">z = Zip.<span style="color:#9900CC;">new</span>
&nbsp;
z.<span style="color:#9900CC;">InstallPackage</span> <span style="color:#008000; font-style:italic;"># calling the template method from the subclass</span></pre></td></tr></table></div>

<p><strong>GOF describes a Hook Method</strong><br />
These are basically just virtual methods which may or may not have code inside them in base classes.<br />
They are a way of telling the concrete subclasses that &#8220;either use the default implementation in the abstract class or override it for some varying algorithm and do something different&#8221;</p>
<p>Implementations without this pattern could be</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p231code6'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p2316"><td class="code" id="p231code6"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Package
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> get_method<span style="color:#006600; font-weight:bold;">&#40;</span>type<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;">if</span> type == <span style="color:#996600;">&quot;Zip&quot;</span> 
&nbsp;
  <span style="color:#008000; font-style:italic;"># create algorithm</span>
  <span style="color:#008000; font-style:italic;"># extract algorithm</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">elsif</span> <span style="color:#008000; font-style:italic;">#some other type</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>which could be amazingly hard to expand for large pieces of code.<br />
I&#8217;m obviously not that experienced a programmer to write hugely scalable projects but I find it a good habit to adopt patterns even while writing smaller snippets.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.scrapcrap.org/dpr1/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Implementing a Chat Server in Ruby</title>
		<link>http://code.scrapcrap.org/implementing-a-chat-server-in-ruby</link>
		<comments>http://code.scrapcrap.org/implementing-a-chat-server-in-ruby#comments</comments>
		<pubDate>Tue, 13 Jan 2009 19:26:17 +0000</pubDate>
		<dc:creator>kitallis</dc:creator>
				<category><![CDATA[Howto]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Chat Server]]></category>
		<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Sockets]]></category>
		<category><![CDATA[TCP]]></category>
		<category><![CDATA[Thin]]></category>

		<guid isPermaLink="false">http://code.scrapcrap.org/?p=87</guid>
		<description><![CDATA[Me and Uncool participated in a &#8216;Linux Challenge&#8217; recently in one of the IT Fest of the University of Delhi.
Although we just managed a Third Prize by some Python heroics in the end by Uncool, we were behind the First team only by a single problem of implementing a chat program using Unix Pipes. We [...]]]></description>
			<content:encoded><![CDATA[<p>Me and <a href="http://uncool.in/">Uncool</a> participated in a &#8216;Linux Challenge&#8217; recently in one of the IT Fest of the <a href="http://en.wikipedia.org/wiki/Nsit">University of Delhi</a>.<br />
Although we just managed a Third Prize by some Python heroics in the end by Uncool, we were behind the First team only by a single problem of implementing a chat program using Unix Pipes. We had little clue about UNIX Pipes so we thought about implementing it by using standard libraries from either Ruby or Python, as they (event organizers) said they would still consider it. Expectedly, they didn&#8217;t have any trace of Ruby on their machines which were running Fedora 9.<br />
Uncool was unsuccessful in implementing it in Python, the documentation was ugly enough.<br />
Reasonably angry, I decided to prove myself why we could have at least won the Second prize without even a drop of sweat.</p>
<p>TCPSocket and TCPServer classes in the Ruby Standard Library are braindead-simple to implement.<br />
<a href="http://www.amazon.com/Ruby-Programming-Language-David-Flanagan/dp/0596516177">The Ruby Programming Language</a> shows how (comments are self-explanatory) :</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p87code10'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p8710"><td class="code" id="p87code10"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># A Multithreaded Server</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'socket'</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># This method expects a socket connected to a client.</span>
<span style="color:#008000; font-style:italic;"># It reads lines from the client, reverses them and sends them back.</span>
<span style="color:#008000; font-style:italic;"># Multiple threads may run this method at the same time.</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> handle_client<span style="color:#006600; font-weight:bold;">&#40;</span>c<span style="color:#006600; font-weight:bold;">&#41;</span>
 <span style="color:#9966CC; font-weight:bold;">while</span> <span style="color:#0000FF; font-weight:bold;">true</span>
   input = c.<span style="color:#CC0066; font-weight:bold;">gets</span>.<span style="color:#CC0066; font-weight:bold;">chop</span>                 <span style="color:#008000; font-style:italic;"># Read a line of input from the client</span>
   <span style="color:#9966CC; font-weight:bold;">break</span> <span style="color:#9966CC; font-weight:bold;">if</span> !input                     <span style="color:#008000; font-style:italic;"># Exit if no more input</span>
   <span style="color:#9966CC; font-weight:bold;">break</span> <span style="color:#9966CC; font-weight:bold;">if</span> input == <span style="color:#996600;">&quot;quit&quot;</span>            <span style="color:#008000; font-style:italic;"># or if the client asks to.</span>
   c.<span style="color:#CC0066; font-weight:bold;">puts</span><span style="color:#006600; font-weight:bold;">&#40;</span>input.<span style="color:#9900CC;">reverse</span><span style="color:#006600; font-weight:bold;">&#41;</span>               <span style="color:#008000; font-style:italic;"># Otherwise, respond to client.</span>
   c.<span style="color:#9900CC;">flush</span>                             <span style="color:#008000; font-style:italic;"># Force our output out</span>
 <span style="color:#9966CC; font-weight:bold;">end</span>
 c.<span style="color:#9900CC;">close</span>                               <span style="color:#008000; font-style:italic;"># Close the client socket</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
server = TCPServer.<span style="color:#CC0066; font-weight:bold;">open</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">2000</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;"># Listen on port 2000</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">while</span> <span style="color:#0000FF; font-weight:bold;">true</span>                             <span style="color:#008000; font-style:italic;"># Servers loop forever</span>
 client = server.<span style="color:#9900CC;">accept</span>                <span style="color:#008000; font-style:italic;"># Wait for a client to connect</span>
 <span style="color:#CC00FF; font-weight:bold;">Thread</span>.<span style="color:#9900CC;">start</span><span style="color:#006600; font-weight:bold;">&#40;</span>client<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>c<span style="color:#006600; font-weight:bold;">|</span>           <span style="color:#008000; font-style:italic;"># Start a new thread</span>
   handle_client<span style="color:#006600; font-weight:bold;">&#40;</span>c<span style="color:#006600; font-weight:bold;">&#41;</span>                    <span style="color:#008000; font-style:italic;"># And handle the client on that thread</span>
 <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p><a href="http://ruby-doc.org/stdlib/libdoc/gserver/rdoc/classes/GServer.html#M000820">Gserver</a>, one of the better standard libraries in Ruby.</p>
<p>More flexible than the socket library, it can be used to implement application level servers, it has a few useful predefined methods like the number of connections, event logging and handles all threading problems by itself, that means multiple users can connect on a single server at once (Asynchronous Socket programming -  which is, where many clients connect to a single server and send input for processing concurrently, the server then handles all the connected clients asynchronously and process the data as and whenever it is available from any of them.)</p>
<p>This little toy Chat Program reads a single input from the client, <a href="http://code.scrapcrap.org/?p=44">shuffles</a> it and sends it back.</p>
<p><strong>CLIENT</strong></p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p87code11'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p8711"><td class="code" id="p87code11"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'socket'</span>                           <span style="color:#008000; font-style:italic;"># Sockets are in standard library</span>
&nbsp;
sock = TCPSocket.<span style="color:#CC0066; font-weight:bold;">open</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;localhost&quot;</span>,<span style="color:#006666;">1234</span><span style="color:#006600; font-weight:bold;">&#41;</span>    <span style="color:#008000; font-style:italic;"># Socket to listen on port 1234</span>
&nbsp;
  l = STDIN.<span style="color:#CC0066; font-weight:bold;">gets</span>                           <span style="color:#008000; font-style:italic;"># Get a single input from console</span>
  sock.<span style="color:#CC0066; font-weight:bold;">puts</span><span style="color:#006600; font-weight:bold;">&#40;</span>l<span style="color:#006600; font-weight:bold;">&#41;</span>                             <span style="color:#008000; font-style:italic;"># Send input to the server</span>
  sock.<span style="color:#9900CC;">flush</span>                               <span style="color:#008000; font-style:italic;"># Force input</span>
  line = sock.<span style="color:#9900CC;">readpartial</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">4096</span><span style="color:#006600; font-weight:bold;">&#41;</span>            <span style="color:#008000; font-style:italic;"># Read server's response</span>
  <span style="color:#CC0066; font-weight:bold;">puts</span> line                                <span style="color:#008000; font-style:italic;"># Display the response to the user</span>
&nbsp;
sock.<span style="color:#9900CC;">close</span>                                 <span style="color:#008000; font-style:italic;"># Close the socket</span></pre></td></tr></table></div>

<p><strong>SERVER</strong></p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p87code12'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p8712"><td class="code" id="p87code12"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'gserver'</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># Algorithm to shuffle a string</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> shuffle<span style="color:#006600; font-weight:bold;">&#40;</span>str<span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
lenth = str.<span style="color:#9900CC;">length</span>
&nbsp;
index = <span style="color:#006600; font-weight:bold;">&#40;</span>lenth<span style="color:#006600; font-weight:bold;">-</span><span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">while</span><span style="color:#006600; font-weight:bold;">&#40;</span>index <span style="color:#006600; font-weight:bold;">&amp;</span>gt;= <span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
&nbsp;
   random_number = <span style="color:#CC0066; font-weight:bold;">rand</span><span style="color:#006600; font-weight:bold;">&#40;</span>lenth<span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
   str<span style="color:#006600; font-weight:bold;">&#91;</span>random_number<span style="color:#006600; font-weight:bold;">&#93;</span>, str<span style="color:#006600; font-weight:bold;">&#91;</span>index<span style="color:#006600; font-weight:bold;">&#93;</span> = str<span style="color:#006600; font-weight:bold;">&#91;</span>index<span style="color:#006600; font-weight:bold;">&#93;</span>, str<span style="color:#006600; font-weight:bold;">&#91;</span>random_number<span style="color:#006600; font-weight:bold;">&#93;</span>
&nbsp;
   index = index <span style="color:#006600; font-weight:bold;">-</span> <span style="color:#006666;">1</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
str
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> Server <span style="color:#006600; font-weight:bold;">&amp;</span>lt; GServer                  <span style="color:#008000; font-style:italic;"># Server class derived from GServer super class</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize<span style="color:#006600; font-weight:bold;">&#40;</span>port=<span style="color:#006666;">1234</span>, <span style="color:#006600; font-weight:bold;">*</span>args<span style="color:#006600; font-weight:bold;">&#41;</span>      <span style="color:#008000; font-style:italic;"># to use the initialize function</span>
      <span style="color:#9966CC; font-weight:bold;">super</span><span style="color:#006600; font-weight:bold;">&#40;</span>port, <span style="color:#006600; font-weight:bold;">*</span>args<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> serve<span style="color:#006600; font-weight:bold;">&#40;</span>io<span style="color:#006600; font-weight:bold;">&#41;</span>                         <span style="color:#008000; font-style:italic;"># Serve method handles connections</span>
&nbsp;
      input = io.<span style="color:#CC0066; font-weight:bold;">gets</span>.<span style="color:#CC0066; font-weight:bold;">chop!</span>             <span style="color:#008000; font-style:italic;"># Get input from client console</span>
      io.<span style="color:#CC0066; font-weight:bold;">puts</span><span style="color:#006600; font-weight:bold;">&#40;</span>shuffle<span style="color:#006600; font-weight:bold;">&#40;</span>input<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span>           <span style="color:#008000; font-style:italic;"># Return the shuffled input onto the client console</span>
      <span style="color:#CC0066; font-weight:bold;">puts</span> input                        <span style="color:#008000; font-style:italic;"># Print the client message </span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
server = Server.<span style="color:#9900CC;">new</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">while</span> <span style="color:#006600; font-weight:bold;">&#40;</span>input = <span style="color:#CC0066; font-weight:bold;">gets</span><span style="color:#006600; font-weight:bold;">&#41;</span>                     <span style="color:#008000; font-style:italic;"># Loop server while user gives an input</span>
&nbsp;
 <span style="color:#9966CC; font-weight:bold;">if</span> input =~ <span style="color:#006600; font-weight:bold;">/</span>start<span style="color:#006600; font-weight:bold;">/</span>
   server.<span style="color:#9900CC;">start</span>                          <span style="color:#008000; font-style:italic;"># Start the server if the user types &quot;init&quot;</span>
&nbsp;
 <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
 <span style="color:#9966CC; font-weight:bold;">if</span> input =~ <span style="color:#006600; font-weight:bold;">/</span>shutdown<span style="color:#006600; font-weight:bold;">/</span>
   server.<span style="color:#9900CC;">shutdown</span>                       <span style="color:#008000; font-style:italic;"># Shut the server down if the user types &quot;shutdown&quot;</span>
&nbsp;
 <span style="color:#9966CC; font-weight:bold;">break</span>
 <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p><a href="http://code.macournoyer.com/thin/">Thin</a> provides a <a href="http://code.macournoyer.com/thin/doc/classes/Thin/Backends/TcpServer.html">TCPServer</a> Socket backend which can also be used for similar purposes. Its pretty much the same except that it uses the <a href="http://rubyeventmachine.com/">EventMachine</a> library for the Network I/O.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.scrapcrap.org/implementing-a-chat-server-in-ruby/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Shuffling</title>
		<link>http://code.scrapcrap.org/shuffling</link>
		<comments>http://code.scrapcrap.org/shuffling#comments</comments>
		<pubDate>Sun, 11 Jan 2009 18:05:37 +0000</pubDate>
		<dc:creator>kitallis</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Fisher-Yates]]></category>
		<category><![CDATA[GUID]]></category>
		<category><![CDATA[Knuth]]></category>
		<category><![CDATA[Random]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Shuffle]]></category>

		<guid isPermaLink="false">http://code.scrapcrap.org/?p=44</guid>
		<description><![CDATA[
I was recently going through a set of commonly asked interview questions and I came across a problem requiring to shuffle a deck of 52 cards in random order. Initially, I found The Knuth or The Fisher Yates shuffle the easiest algorithm to implement.
The Knuth Shuffle makes use of a certain set  of random numbers for [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: left;"><img class="alignnone size-full wp-image-68" title="Set_0f_Cards" src="http://code.scrapcrap.org/wp-content/uploads/2009/01/cards01.jpg" alt="Set_0f_Cards" width="369" height="155" /></p>
<p style="text-align: left;">I was recently going through a set of commonly asked interview questions and I came across a problem requiring to shuffle a deck of 52 cards in random order. Initially, I found <a href="http://en.wikipedia.org/wiki/Knuth_shuffle">The Knuth or The Fisher Yates shuffle</a> the easiest algorithm to implement.</p>
<p style="text-align: left;">The Knuth Shuffle makes use of a certain set  of random numbers for creating randomness. Implementing it as Code, obviously required me to make use of the rand() function.</p>
<p style="text-align: left;">Here&#8217;s the actual description of the algorithm from The Art of Computer Programming, Volume 2: Seminumerical Algorithms, page:145. Third Edition. D.E. Knuth</p>
<blockquote><p>Let X1, X2, …, Xt be a set of t numbers to be shuffed.</p>
<p>P1. [Initialize.] Set j ← t.<br />
P2. [Generate U.] Generate a random number U, uniformly distributed between zero and one.<br />
P3. [Exchange.] Set k ← [jU] + 1. (Now k is a random integer, between 1 and j. Exchange Xk and Xj.<br />
P4. [Decrease j.] Decrease j by 1. If j &gt; 1, return to step P2.</p></blockquote>
<p>I used my favourite language Ruby to write the code and came up with this :</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p44code15'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p4415"><td class="code" id="p44code15"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">array</span> = <span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>..52<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">to_a</span>
&nbsp;
lenth = <span style="color:#CC0066; font-weight:bold;">array</span>.<span style="color:#9900CC;">length</span>
&nbsp;
index = <span style="color:#006600; font-weight:bold;">&#40;</span>lenth<span style="color:#006600; font-weight:bold;">-</span><span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">while</span><span style="color:#006600; font-weight:bold;">&#40;</span>index <span style="color:#006600; font-weight:bold;">&amp;</span>gt;= <span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
&nbsp;
  random_number = <span style="color:#CC0066; font-weight:bold;">rand</span><span style="color:#006600; font-weight:bold;">&#40;</span>index<span style="color:#006600; font-weight:bold;">+</span><span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
  <span style="color:#CC0066; font-weight:bold;">array</span><span style="color:#006600; font-weight:bold;">&#91;</span>random_number<span style="color:#006600; font-weight:bold;">&#93;</span>, <span style="color:#CC0066; font-weight:bold;">array</span><span style="color:#006600; font-weight:bold;">&#91;</span>index<span style="color:#006600; font-weight:bold;">&#93;</span> = <span style="color:#CC0066; font-weight:bold;">array</span><span style="color:#006600; font-weight:bold;">&#91;</span>index<span style="color:#006600; font-weight:bold;">&#93;</span>, <span style="color:#CC0066; font-weight:bold;">array</span><span style="color:#006600; font-weight:bold;">&#91;</span>random_number<span style="color:#006600; font-weight:bold;">&#93;</span>
&nbsp;
  index = index <span style="color:#006600; font-weight:bold;">-</span> <span style="color:#006666;">1</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#CC0066; font-weight:bold;">array</span></pre></td></tr></table></div>

<p>One of the problem I found was the use of the rand() function.<br />
The use of a randomize function in real life situation is not ideal, say, in a game of Poker(online). One can easily sync the time of our clock to that of the server, If the randomize function is seeded with the number of milliseconds from the system clock as was in the case of the ASF Software&#8217;s Poker product.</p>
<p>A Modulus operator is used for restricting the numbers in a particular range. Like in the GNU C Library&#8217;s (GlibC) <a href="http://www.google.com/codesearch/p?hl=en#WbTnQ5DcqbM/glibc-2.1.3/string/strfry.c&amp;q=strfry">strfry()</a> which can be used for randomizing strings. </p>
<p>From Wikipedia :</p>
<blockquote><p>Doing a Fisher-Yates shuffle involves picking uniformly distributed random integers from various ranges. Most random number generators, however—whether true or pseudorandom—will only directly provide numbers in some fixed range, such as, say, from 0 to 232−1. A simple and commonly used way to force such numbers into a desired smaller range is to apply the modulo operator; that is, to divide them by the size of the range and take the remainder. However, the need, in a Fisher-Yates shuffle, to generate random numbers in every range from 0–1 to 0–N pretty much guarantees that some of these ranges will not evenly divide the natural range of the random number generator. Thus, the remainders will not always be evenly distributed and, worse yet, the bias will be systematically in favor of small remainders.</p></blockquote>
<p>Googling around turned out that sorting it by using <a href="http://en.wikipedia.org/wiki/UUID">UUID&#8217;s</a> as a source of random numbers was more easier to implement.<br />
Ruby offers a <a href="http://raa.ruby-lang.org/project/ruby-guid/">library</a> for generating UUID&#8217;s which uses /dev/urandom on *nix types systems to generate random numbers.<br />
A GUID can be created by these two lines.</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p44code16'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p4416"><td class="code" id="p44code16"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'guid'</span> 
&nbsp;
g2 = Guid.<span style="color:#9900CC;">new</span>  <span style="color:#008000; font-style:italic;">#a unique GUID every time</span></pre></td></tr></table></div>

<p>It&#8217;s typically not faster, as sorting would be O(n log n) compared to the O(n) (linear time) for the Knuth Shuffle.</p>
<p><a href="http://mathworld.wolfram.com/Shuffle.html">Wolfram MathWorld</a> has a few mathematical shuffling algorithms and randomization techniques for further mathematical reference.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.scrapcrap.org/shuffling/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

