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

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

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=241</guid>
		<description><![CDATA[I keep seeing many programmers from different backgrounds are unable to get what Ruby symbols are, and though I do know that there are many great posts regarding this topic, and actually my intent is not to increase them by one   , but I feel I have to clear few points regarding them.
So [...]]]></description>
			<content:encoded><![CDATA[<p>I keep seeing many programmers from different backgrounds are unable to get what Ruby symbols are, and though I do know that there are many <a href="http://www.google.com/search?hl=en&#038;q=ruby+symbols+&#038;btnG=Google+Search&#038;aq=f&#038;oq=">great posts</a> regarding this topic, and actually my intent is not to increase them by one <img src='http://www.khelll.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  , but I feel I have to clear few points regarding them.<br />
So I&#8217;m trying to answer 2 important question here: <strong>What are Ruby symbols?</strong> and <strong>When to use them?</strong></p>
<h2>What are Ruby symbols?</h2>
<p>Well, according to the <a href="http://www.ruby-doc.org/core/classes/Symbol.html">API documentation</a>:</p>
<blockquote><p>Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :&#8221;string&#8221; literals syntax, and by the various to_sym methods. The same Symbol object will be created for a given name or string for the duration of a program&#8217;s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts. </p></blockquote>
<p>Let&#8217;s walk over this long quote, point by point, but let&#8217;s first list all the points it has:</p>
<p>1-Symbol objects represent names and some strings inside the Ruby interpreter.<br />
2-They are generated using the :name and :&#8221;string&#8221; literals syntax, and by the various to_sym methods.<br />
3-The same Symbol object will be created for a given name or string for the duration of a program&#8217;s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.</p>
<p>I&#8217;ll start with the 2nd point then get back to the rest, just before I do, please fire your irb:</p>
<p>We can create a symbol with various ways:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># Normal way, just prefix a token with ':'</span>
greeting = <span style="color:#ff3333; font-weight:bold;">:hi</span> <span style="color:#008000; font-style:italic;">#=&gt; :hi</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># Multi token symbol </span>
another_greeting = :<span style="color:#996600;">&quot;hello man&quot;</span> <span style="color:#008000; font-style:italic;">#=&gt; :&quot;hello man&quot;</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># Use the .to_sym if it's defined for your object class</span>
<span style="color:#008000; font-style:italic;"># For example .to_sym is defind in String class</span>
a_third_greeing = <span style="color:#996600;">&quot;howdy&quot;</span>.<span style="color:#9900CC;">to_sym</span> <span style="color:#008000; font-style:italic;">#=&gt; :howdy</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># Using %s[ ]</span>
<span style="color:#006600; font-weight:bold;">%</span>s<span style="color:#006600; font-weight:bold;">&#91;</span>a 4th one<span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#008000; font-style:italic;">#=&gt; :&quot;a 4th one&quot;</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># We can also cast a symbol to string with to_s</span>
<span style="color:#ff3333; font-weight:bold;">:ds</span>.<span style="color:#9900CC;">to_s</span> <span style="color:#008000; font-style:italic;">#=&gt; &quot;ds&quot;</span></pre></div></div>

<p>That was the easy part, now let&#8217;s get back to the first point, it says: &#8220;Symbol objects represent names and some strings inside the Ruby interpreter.&#8221; , what does that mean exactly?</p>
<p>In computer science there is a term called: <a href="http://en.wikipedia.org/wiki/Symbol_table">Symbol table</a>, where the compiler or the interpreter of the language stores all the identifiers of a source code in that table to reference them -specifically to be referenced by the <a href="http://en.wikipedia.org/wiki/Abstract_syntax_tree">Abstract Syntax Tree</a>(AST).<br />
Actually the data structure that represents the symbol table varies from one interpreter to another, but what we care for is Ruby, in Ruby, the symbol table stores various things like method names and symbol names(we will check why Ruby does so later on), <strong>and the value of a symbol is a unique integer value, that can&#8217;t be changed</strong>.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># Not working on ruby 1.9</span>
<span style="color:#ff3333; font-weight:bold;">:ds</span>.<span style="color:#9900CC;">to_i</span> <span style="color:#008000; font-style:italic;">#=&gt; 28777</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># Notice the value of the symbol is not its object id</span>
<span style="color:#ff3333; font-weight:bold;">:ds</span>.<span style="color:#9900CC;">object_id</span> <span style="color:#008000; font-style:italic;">#=&gt; 287778</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># Symbol values can't be changed</span>
<span style="color:#ff3333; font-weight:bold;">:ds</span> = <span style="color:#006666;">3</span> <span style="color:#008000; font-style:italic;">#SyntaxError: compile error</span></pre></div></div>

<p>Now let&#8217;s take more in depth example, let&#8217;s explore the symbol table:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># Let's check what symbols names start with 'hello'</span>
<span style="color:#CC00FF; font-weight:bold;">Symbol</span>.<span style="color:#9900CC;">all_symbols</span>.<span style="color:#9900CC;">collect</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> x.<span style="color:#9900CC;">to_s</span><span style="color:#006600; font-weight:bold;">&#125;</span>.<span style="color:#9900CC;">grep</span> <span style="color:#006600; font-weight:bold;">/</span>^hello.<span style="color:#006600; font-weight:bold;">*</span>$<span style="color:#006600; font-weight:bold;">/</span> <span style="color:#008000; font-style:italic;">#=&gt; [&quot;hello&quot;]</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># Now let's define a new dummy class and add  a new method called 'hello_world'</span>
<span style="color:#9966CC; font-weight:bold;">class</span> Dummy; <span style="color:#9966CC; font-weight:bold;">def</span> hello_world; <span style="color:#9966CC; font-weight:bold;">end</span> ; <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#008000; font-style:italic;">#=&gt; nil</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># Check again.</span>
<span style="color:#CC00FF; font-weight:bold;">Symbol</span>.<span style="color:#9900CC;">all_symbols</span>.<span style="color:#9900CC;">collect</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> x.<span style="color:#9900CC;">to_s</span><span style="color:#006600; font-weight:bold;">&#125;</span>.<span style="color:#9900CC;">grep</span> <span style="color:#006600; font-weight:bold;">/</span>^hello.<span style="color:#006600; font-weight:bold;">*</span>$<span style="color:#006600; font-weight:bold;">/</span> <span style="color:#008000; font-style:italic;">#=&gt; [&quot;hello&quot;, &quot;hello_world&quot;]</span></pre></div></div>

<p>As you can see, when we defined the class &#8216;Dummy&#8217; and more specifically when we defined the &#8216;hello_world&#8217; method, it was added to the symbol table.<br />
Let&#8217;s take another example:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC00FF; font-weight:bold;">Symbol</span>.<span style="color:#9900CC;">all_symbols</span>.<span style="color:#9900CC;">size</span> <span style="color:#008000; font-style:italic;">#=&gt; 3329</span>
<span style="color:#ff3333; font-weight:bold;">:koko</span> <span style="color:#008000; font-style:italic;">#=&gt; :koko</span>
<span style="color:#CC00FF; font-weight:bold;">Symbol</span>.<span style="color:#9900CC;">all_symbols</span>.<span style="color:#9900CC;">size</span> <span style="color:#008000; font-style:italic;">#=&gt; 3330</span></pre></div></div>

<p>Now let&#8217;s take the last point : &#8220;The same Symbol object will be created for a given name or string for the duration of a program&#8217;s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.&#8221; ,so: Fred is :Fred wherever you see it and no matter what the context it comes in:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">k = <span style="color:#ff3333; font-weight:bold;">:Fred</span>  <span style="color:#008000; font-style:italic;">#=&gt; :Fred                  </span>
<span style="color:#9966CC; font-weight:bold;">module</span> M; Cons = <span style="color:#ff3333; font-weight:bold;">:Fred</span>; <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#008000; font-style:italic;">#=&gt; :Fred</span>
k.<span style="color:#9900CC;">object_id</span> <span style="color:#008000; font-style:italic;">#=&gt; 287498</span>
<span style="color:#6666ff; font-weight:bold;">M::Cons</span>.<span style="color:#9900CC;">object_id</span> <span style="color:#008000; font-style:italic;">#=&gt; 287498</span></pre></div></div>

<h2>When to use Ruby symbols?</h2>
<p>Well, this might be the one million dollars question, and that&#8217;s initially why i wrote this post for. You also might be wondering, why have <a href="http://en.wikipedia.org/wiki/Yukihiro_Matsumoto">Matz</a> chosen to give us this low level introspection in the language by allowing me to work with the interpreter stuff?</p>
<p>The answer is divided in 2 parts:</p>
<p>1- Efficiency. 2-  Metaprogramming(reflection).</p>
<h3> Efficiency </h3>
<p>We will talk about efficiency at first place,so let&#8217;s check this snippet of code:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># Some programmer would do this</span>
<span style="color:#9966CC; font-weight:bold;">if</span> name == <span style="color:#996600;">&quot;khaled alhabache&quot;</span></pre></div></div>

<p>The snippet of code above is really costive, in terms of memory and efficiency:<br />
1-Comparing 2 strings is costive, specially when the 2 strings are long.<br />
2-Reserving &#8220;changeable&#8221; amount of memory, 16 bytes in our case to instantiate &#8220;Khaled alhabache&#8221;.<br />
3-The GC would have to clean this &#8220;Khaled alhabache&#8221; later on.</p>
<p>What about doing :</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># This is what i call it &quot;a cleaner approach&quot;</span>
<span style="color:#9966CC; font-weight:bold;">if</span> name.<span style="color:#9900CC;">to_sym</span> == :<span style="color:#996600;">&quot;khaled alhabache&quot;</span></pre></div></div>

<p>Now what we did is:<br />
1-Comparing 2 integers(the value of a symbol is integer) which is cheaper.<br />
2-Reserving memory 4 bytes for :&#8221;Khaled alhabache&#8221; symbol, cause a symbol is an integer finally.<br />
3-The GC would not have to clean this :&#8221;Khaled alhabache&#8221; symbol, cause symbols don&#8217;t get deleted till program exits.</p>
<p><strong>So use symbols as much as you can, and avoid using stings as much as you can, but take extra care of defining thousands of symbols, cause as mentioned: symbols don&#8217;t get deleted till program exits, and thus they stick in memory.</strong></p>
<h3>Metaprogramming and symbols</h3>
<p>Well working with <a href="http://www.khelll.com/blog/ruby/ruby-and-metaprogramming/">metaprogramming</a> in Ruby is really nice, you can do something like:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">to = <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:to_s</span> , <span style="color:#ff3333; font-weight:bold;">:to_f</span> , <span style="color:#ff3333; font-weight:bold;">:to_r</span><span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#008000; font-style:italic;">#=&gt; [:to_s, :to_f, :to_r]</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># Notice the use of symbols with reflection -Ex with 'send' method </span>
to.<span style="color:#9900CC;">each</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>method<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;#{method} =&gt; #{5.send method}&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#008000; font-style:italic;"># to_s =&gt; 5</span>
<span style="color:#008000; font-style:italic;"># to_f =&gt; 5.0</span>
<span style="color:#008000; font-style:italic;"># to_r =&gt; 5</span></pre></div></div>

<p>Without symbols, you would never be able to use reflection techniques like &#8217;send&#8217;, otherwise how can you invoke methods dynamically?, also without symbols, you would never be able to use introspection techniques like &#8216;respond_to?&#8217;</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">5.<span style="color:#9900CC;">respond_to</span>? <span style="color:#ff3333; font-weight:bold;">:slice</span> <span style="color:#008000; font-style:italic;">#=&gt; false</span>
5.<span style="color:#9900CC;">respond_to</span>? <span style="color:#ff3333; font-weight:bold;">:to_f</span> <span style="color:#008000; font-style:italic;">#=&gt; true</span></pre></div></div>

<p><strong>Update, a respond to readers comments</strong>:<br />
It&#8217;s true that you can do something like :</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">5.<span style="color:#9900CC;">respond_to</span>? <span style="color:#996600;">&quot;to_f&quot;</span> <span style="color:#008000; font-style:italic;">#=&gt; true</span></pre></div></div>

<p>But what&#8217;s happening is that Ruby is casting it for you, but why to reserve extra memory to send it as a string?</p>
<p>For guys who are objecting on memory efficiency with symbols, I strongly recommend reading <a href="http://glu.ttono.us/articles/2005/08/19/understanding-ruby-symbols">this</a> post also.</p>
<p>I hope I could help you understand what Ruby symbols are and why they are used for, specially of you who are coming from other programing backgrounds.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.khelll.com/blog/ruby/ruby-symbols/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>
