<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><!--Generated by Squarespace Site Server v5.5.4 (http://www.squarespace.com/) on Thu, 16 Jul 2009 05:02:28 GMT--><feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/"><title>Me Dev, You Jane - Ruby</title><subtitle>Blog</subtitle><id>http://medevyoujane.com/blog/</id><link rel="alternate" type="application/xhtml+xml" href="http://medevyoujane.com/blog/" /><updated>2009-06-13T16:40:40Z</updated><generator uri="http://www.squarespace.com/" version="Squarespace Site Server v5.5.4 (http://www.squarespace.com/)">Squarespace</generator><link rel="self" href="http://feeds.feedburner.com/MeDevYouJane/Ruby" type="application/atom+xml" /><entry><title>Setting up a Ruby 1.9 Sandbox on Leopard</title><category term="Ruby" /><id>http://medevyoujane.com/blog/2008/8/21/setting-up-a-ruby-19-sandbox-on-leopard.html</id><link rel="alternate" type="text/html" href="http://medevyoujane.com/blog/2008/8/21/setting-up-a-ruby-19-sandbox-on-leopard.html" /><author><name>Jón Grétar Borgþórsson</name></author><published>2008-08-21T09:44:07Z</published><updated>2008-08-21T09:44:07Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>The next version of Ruby is right around the corner and it is propably time to start getting used to the changes and start making your code compatable to the new version. Since it's not a good idea to overwrite your existing ruby installation you should propably install a Ruby 1.9 sandbox with the following directions. Although I did this on a Mac OS X.5 machine the directions should work fine for Linux. Lets start with downloading Ruby and installing in <em>/opt</em>.</p>

<pre><code>cd /tmp
curl http://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.0-3.tar.gz | tar zx
cd ruby-1.9.0-r18217

autoconf
./configure --prefix=/opt/ruby19
make
sudo make install
</code></pre>

<p>Now lets set up a command that puts you in the 1.9 sandbox when needed. Open up the file <em>.profile</em> in your home directory or create it if it does not exist. Add the following line</p>

<pre><code>alias ruby19="export PATH=/opt/ruby19/bin:$PATH"
</code></pre>

<p>Close the Terminal window and open up again. Now everytime you need to put a terminal window into the Ruby 1.9 mode just type in the command <code>ruby19</code>. Try it out with the command <code>ruby -v</code> and you should see the reply:</p>

<pre><code>ruby 1.9.0 (2008-07-25 revision 18217) [i686-darwin9.4.0]
</code></pre>

<p>Now just have fun in the sandbox. Remember that there now is a seperate gem repository so you need to get the gems you need with the <code>gem</code> command. For info on changes in Ruby 1.9 take a look at the <a href="http://slideshow.rubyforge.org/ruby19.html">Ruby 1.9: What To Expect</a> or <a href="http://codefluency.com/articles/2008/04/13/migrating-to-ruby-1-9/">Migrating to Ruby 1.9</a> slideshows.</p>

<script src="http://feeds.feedburner.com/~s/MeDevYouJane?i=http://medevyoujane.com/blog/2008/8/21/setting-up-a-ruby-19-sandbox-on-leopard.html" type="text/javascript" charset="utf-8"></script>
]]></content></entry><entry><title>Erlang Introduction (For the Ruby Guy) part 3</title><category term="Erlang" /><category term="Ruby" /><id>http://medevyoujane.com/blog/2008/8/17/erlang-introduction-for-the-ruby-guy-part-3.html</id><link rel="alternate" type="text/html" href="http://medevyoujane.com/blog/2008/8/17/erlang-introduction-for-the-ruby-guy-part-3.html" /><author><name>Jón Grétar Borgþórsson</name></author><published>2008-08-17T14:04:07Z</published><updated>2008-08-17T14:04:07Z</updated><content type="html" xml:lang="en-US"><![CDATA[<h3>Processes</h3>

<p>In Erlang you world revolves around processes. Not to be confused with OS processes. Here we are talking about highly light weight threads that can quickly be started and shut down. These are a lot faster and lighter that threads you may be used to from Ruby and you will use them quite a lot more than usually happens in Ruby. The best part is that this great power of Erlang is one of the simplest things to do. You just simply use the <em>spawn(module, function, [parameters])</em> command to start a function and it starts it as a process. Really thats it. Lets see an example of this by starting the recurse command from part 2: <code>P1 = spawn(demo,recurse,[[1,2,3]]).</code>. Now this process started and ended within a second but imagine if this would have been some call to some webserver taking up to a few seconds. There the process would have done it's thing and the creating function continues doing it's thing without having to hang around for results.</p>

<p>This is how you should do your Erlang programs. You should avoid as much as you can having your program waiting for some action to complete. Instead you should have a bunch of processes communicating with each other.</p>

<h3>Sending and Receiving Messages</h3>

<p>Now. It's not enough in most cases to just spawn the process and let it run until it finishes. Often you must talk to that process and as they do not share memory with each other they need to talk to each other by passing messages. Luckily this also is as simple as it gets.</p>

<p>The return value of a spawn function is the Pid of the Process. In the example before we bound the Pid to variable <em>P1</em>. We then could just send a message to it simply by saying <code>P1 ! [1,2,3,4].</code>. If we expect a response back we often send our own Pid within the message and we can get the Pid of current process with the command <em>self()</em>. In that case the message might look like <code>P1 ! {helloworld, self()}.</code>.</p>

<p>It's no use sending a message if the receiving process is not listening. Enter the <em>receive</em> consturct. The receiver waits for a message and when it receives that message it tries matching it to a pattern and runs the corresponding actions. Lets look at a receive block.</p>

<pre><code>receive
  [Head|TheRest] -&gt;
    io:format("Got a list with the head: ~p ~n",[Head]);
  {helloworld, CallingPid} -&gt;
    io:format("Got a hello world. Saying hello back. ~p ~n"),
    CallingPid ! {response, "Hi Back"};
  MatchAll -&gt;
    io:format("Error: Dont know what do do with ~p ~n",[MatchAll])
end.
</code></pre>

<p>Here we have 3 possible messages to receive. This works in general much like when we define multiple versions of the same function. </p>

<h3>Registering</h3>

<p>One thing that I will mention before giving an example of using processes is the concept of registering process under a name. Often it's not convienient to store a Pid in a variable since variables only exist within a function. There we register the Pid under a name with the command <em>register(Name, Pid)</em>. For example we could call <code>register(servername, P1).</code> and from now on we can always make the call <code>servername ! {helloworld, self()}.</code> from anywhere inside that node.</p>

<h3>A Simple Example of Processes</h3>

<p>Lets take a look at an example code. Lets open our demo.erl from <a href="http://medevyoujane.com/blog/2008/8/10/erlang-introduction-for-the-ruby-guy-part-2.html">Part 2</a> and add <em>start_server/0, start_server/0, remote_convert/1, server_loop/0</em> to the exports. Go to the end of the file and enter the following code:</p>

<pre><code>start_server() -&gt;
  Pid = spawn(demo, server_loop, []),
  register(converter, Pid).

stop_server() -&gt;
  converter ! shutdown
  unregister(converter).

server_loop() -&gt;
  receive
    {convert, cm, Value, CallingPid} -&gt;
      CallingPid ! {inch, Value / 2.54},
      server_loop();
    {convert, inch, Value, CallingPid} -&gt;
      CallingPid ! {cm, Value * 2.54},
      server_loop();
    shutdown -&gt;
      true;
    MatchAll -&gt;
      io:format("Got a message I don't understand. ~n"),
      server_loop()
  end.

remote_convert({Unit, Value}) -&gt;
  converter ! {convert, Unit, Value, self()},
  receive
    {NewUnit, NewValue} -&gt;
      io:format("Result: ~p ~p~n", [NewUnit,NewValue]);
    error -&gt;
      ok
  end.
</code></pre>

<p>Lets take a look what happens here. We start by compiling and running <code>demo:start_server().</code> that spawns <em>server_loop/0</em> as a process and registers the Pid as <em>converter</em>. Next up is <em>stop_server/0</em> that sends a message to the server asking it to shutdown. Third is <em>server_loop/0</em> has a receive block that waits for 4 matching messages. First 2 are tuples requesting a unit conversion. It converts and sends a message back and then calls itself so it can wait for the next message. The shutdown message really does nothing except not calling for the loop to repeat. MatchAll will handle all other messages and write out an error.</p>

<p><em>remote_convert/1</em> then manages calling the server and then waits for a message back. Lets try it out by running <code>demo:remote_convert({inch,1}).</code> and you should get a message back.</p>
]]></content></entry><entry><title>Erlang Introduction (For the Ruby Guy) part 2</title><category term="Erlang" /><category term="Ruby" /><id>http://medevyoujane.com/blog/2008/8/10/erlang-introduction-for-the-ruby-guy-part-2.html</id><link rel="alternate" type="text/html" href="http://medevyoujane.com/blog/2008/8/10/erlang-introduction-for-the-ruby-guy-part-2.html" /><author><name>Jón Grétar Borgþórsson</name></author><published>2008-08-10T20:29:11Z</published><updated>2008-08-10T20:29:11Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>Here is the second installment of the introduction to Erlang. In the <a href="http://medevyoujane.com/blog/2008/8/6/erlang-introduction-for-the-ruby-guy-part-1.html">first part</a> I introduced you to some of the basics in the Erlang language and now it is time to get to know more of the fun parts of the language. Like the first part this is not supposed to be a tutorial. I am simplifying things here and there is a lot more you should know if you want to do an actual program in erlang. I highly recommend that you check out Kevin's <a href="http://pragprog.com/screencasts/v-kserl/erlang-in-practice">Erlang in Practice</a> screencast, Joe Armstrong's <a href="http://www.pragprog.com/titles/jaerlang/programming-erlang">Programming Erlang</a> book or the excellent documentation on the <a href="http://www.erlang.org/doc/">erlang website</a>.</p>

<h3>Funs</h3>

<p>Funs are basically blocks. And much like you do in Ruby you will use funs a lot. A simple example of a fun would be:</p>

<pre><code>Double = fun(X) -&gt; X*2 end.
</code></pre>

<p>Then you could make the call <code>Double(10).</code> and the result would be <em>20</em>. Much like you do in Ruby you will often use Funs as parameters to functions. An example of a function that takes a fun is <em>lists:map</em>. This is a non object oriented version of Ruby's Array.map. It's first parameter is the fun to be run on each element and the next element is the list itself. Here we would make the call:</p>

<pre><code>lists:map(fun(X) -&gt; X*2 end, [1,2,3]).
</code></pre>

<p>To create a new list with each element multiplied by 2. Another way to get the same result are by using list comprehensions.</p>

<h3>List Comprehension</h3>

<p>List Comprehensions are a great feature to create lists or manipulate lists. Lets start with the simple expression </p>

<pre><code>[X*2 || X &lt;- [1,2,3]].
</code></pre>

<p>This would create a new list with each element doubled. In english this would read "<em>double each X where X is [1,2,3]</em>". What is before || is called the expression and what comes after is referred to as the qualifiers. There can be multiple qualifiers like the example </p>

<pre><code>[X || X &lt;- [1,2,3,4], X &gt; 2].
</code></pre>

<p>This would give out the result [3,4]. Here we the english term would be "<em>display X where X is [1,2,3,4] and X is greater than 2</em>". </p>

<p>A great example of how to use this can be read at <a href="http://en.wikibooks.org/wiki/Erlang_Programming/List_Comprehensions">WikiBooks</a>. Here they give an example of using list comprehensions to solve an equation. The output of:</p>

<pre><code>[ {X,Y} || X &lt;- [1,2,3,4], Y &lt;- [1,2,3,4], X*X == Y].
</code></pre>

<p>Would be <em>[{1,1},{2,4}]</em> and should be read "<em>A tuple with the values X and Y where X is [1,2,3,4] and Y is [1,2,3,4] and where X time X equals Y</em>". And how cool is that.</p>

<p>A type of list comprehension is also used in the powerful mnesia database system to query results instead of SQL. I highly recommend that you get to know it well.</p>

<h3>Modules and Functions</h3>

<p>The modules are really a collection of functions if you simplify things. There are differences of course since it's not objects you are working with. Lets just start with a simple module  from the Erlang website. You can put this in a file called <em>demo.erl</em> and run the command <code>erl</code> in the same directory. You then compile the file typing <code>c(demo).</code> in the Eshell and run it by entering <code>demo:double(2).</code> to get the result <em>4</em>.</p>

<pre><code>-module(demo).
-export([double/1]).

double(X) -&gt;
  times(X, 2).

times(X, N) -&gt;
  X * N.
</code></pre>

<p>The first line is the name of the module. This must match the filename with the .erl extension excluded. </p>

<p>The second line is a list of what functions are exported. Only exported functions can be called from other modules. The list includes the function name and its <em>arity</em>. The arity states the number of parameters the function calls. If you want to export both functions the line would read <code>-export([double/1,times/2]).</code>. Note that you can have 2 functions with the same name but different arity and you would then have to export both versions.</p>

<p>Next up are the functions. This is pretty self explanatory. First up is the functions <em>double</em> that take one parameter and calls the second function <em>times</em>. Times takes 2 parameters and multiplies together. </p>

<p>One thing to notice is the dot (.) at the end. The dot says that this function is done. If this was a multi line function each line would end with a comma (,) except the last line that would end on either a dot or a semicolon (;) if the same function with the same arity is defined. Now this may sound a but confusing but lets look at how it works. The boss has asked me to change the double function that the whole company stands or falls with so that it would give me an error message if I decide to be a fool and double the number 0. If I were in ruby I might just add an if statement inside the function but this is erlang and things are done differently. Lets delete the whole double function and replace it with the following and recompile:</p>

<pre><code>double(0) -&gt;
  io:format("Only a fool would double a zero ~n"),
  0;
double(X) -&gt;
  times(X, 2).
</code></pre>

<p>Here we see basically the same function twice. What happens here is really the same as the pattern matching in part 1. if we make he call <code>demo:double(2).</code> the erlang system first tries to match with double(0). Since 0 == 2 can not match it goes down do double(N). There it sees that it it can make true the statement X == 2 if X holds the value 2 and runs that function. Here we also see the the uses of commas and semicolons. First line in <em>double(0)</em> prints out a message to STDOUT and then the comma says that another statement is to follow. Then put out a single <em>0</em> because like in ruby the last statement is the return value of the function. This is followed by a semicolon to say that the function is over but that the same function will return but for a different value (It's actually not that simple but it's the simplest way to explain the behavior). Then at the end we have a period to say that all version of the function is over. </p>

<p>Another common way of usage is using tuples. Lets add convert/1 to our exports at the start of the file, add the following to the end of the file and recompile.</p>

<pre><code>convert({cm, Value}) -&gt;
  {inch, Value / 2.54};
convert({inch, Value}) -&gt;
  {cm, Value * 2.54}.
</code></pre>

<p>Here we call <em>convert/1</em> with a tuple. The first element in the tuple is the current unit of length and the second element is the value in that unit. It then returns a tuple with the new unit and the converted value. So the call <code>demo:convert({inch, 1}).</code> would give the result <em>{cm, 2.54000}</em>. Here we see in a great manner why we often have the first element in the tuple define what the whole tuple is like I mentioned in part 1.</p>

<h3>Recursing Functions</h3>

<p>One thing that, if you would do in ruby, would call for a lynching mob after you are recursive functions. In Erlang it's standard practice. Functions quite frequently call themselves. Lets look at an example of recursion by adding this to our demo.erl. Don't forget to export <em>recurse/1</em>.</p>

<pre><code>recurse([]) -&gt;
    io:format("All done.~n");
recurse([First|TheRest]) -&gt;
    io:format("Value: ~p ~n", [First]),
    recurse(TheRest).
</code></pre>

<p>When we call this with an list like so: <code>demo:recurse([1,2,3]).</code>. it will first try to match with <em>recurse([])</em> and be unable to do so since it's not an empty list. It will however match with the second function and create 2 variables. The variable <em>First</em> will hold the first value in the list and will be printed out but <em>TheRest</em> will hold the rest of the list. Then it calls itself again with the shortened <em>TheRest</em> list. In the end the list will be empty and match the first definition of <em>recurse/1</em>.</p>

<h3>Conclusion</h3>

<p>This should be good for now. Next article will go into processes mainly and give a little overview over the OTP principles.</p>
]]></content></entry><entry><title>Erlang Introduction (For the Ruby Guy) part 1</title><category term="Erlang" /><category term="Ruby" /><id>http://medevyoujane.com/blog/2008/8/6/erlang-introduction-for-the-ruby-guy-part-1.html</id><link rel="alternate" type="text/html" href="http://medevyoujane.com/blog/2008/8/6/erlang-introduction-for-the-ruby-guy-part-1.html" /><author><name>Jón Grétar Borgþórsson</name></author><published>2008-08-06T19:41:27Z</published><updated>2008-08-06T19:41:27Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>The purpose here is to write a basic beginners info for erlang. It's not in any way a tutorial but it's aim is to peak your interest in the language. This is aimed at Ruby programmers and tries to give a good overview of the basic differences and similarities. Both in programming and thinking. </p><p>Erlang is a wonderful tool to learn and gives you the same enjoyable programming experience as most have with Ruby. And it's a great match to use them together in a product. Ruby for the front end to ease making a good user experience with trusty old Erlang in the background making sure everything is rock stable. </p><p>The power of Erlang lies in it's ability to be scalable and stable. To put it bluntly. If your Erlang application is unstable and does not scale well then you have done something wrong. </p><h3>The Shell</h3><p>We start off on a familiar ground. The main Erlang executable is the command erl. This should instantly feel as home to Rubyist and remind of trusty old irb. What it can not do however is create the modules and functions. It can only call them. However it's powerful and you should expect to spend a lot of your time inside there. Remember to end your statements with a period to execute them.</p><h3>Variables</h3><p>Variable start with a capital letter. The first thing that shocks people is the fact that you can only set a variables once. Thus typing <span style="font-weight: bold;"><em>Var1 = 1</em></span> and then immediately <span style="font-weight: bold;"><em>Var1 = 2</em></span>. would give you an error. Think of it as a strength though rather than a problem. The simple, money back, guarantee is that this will never be a problem for you and you won't need to think about this since functions are short and variables only exist inside the function. What usually happens is that people start actually liking having the variables single-assigned since it tends to simplify things and reduce errors.</p><h3>Atoms are Symbols</h3><p>Atoms start with a downcase letter or are enclosed in single quotes. They can not hold any value and represent only themselves. They are basically the same as symbols in Ruby. One thing to remember is that atoms do not disappear from memory after being created so if you in some way create them dynamically you may fill up your memory after a while. This may not sound like a problem at first but remember that your goal is probably to create an application that will run for months or even years without being restarted.</p><h3>Lists and Tuples</h3><p>Lists and Tuples are similar in many ways. Both represent a collection of elements. The difference is that lists have variable number of elements while tuples have fixed number of elements. Lists are defined between <em>[...]</em> while tuples are between <em>{...}</em> I read somewhere that lists are like arrays while tuples are like hashes. That is 100% totally incorrect. Tuples are nothing like hashes. The most common use of tuples you will see is that the first element is a atom that explains the rest of the tuple. For example the tuple <span style="font-weight: bold;"><em>{error, 404, "File Not Found"}</em></span>. Often you will also use a list of tuples. For example <span style="font-weight: bold;"><em>[{person,"Steve"},{person,"Joe"}]</em></span>. How this all matters is best explained in the next section.</p><h3>Matching (or how = is not =)</h3><p>The equal sign behaves quite a bit different from what you are probably used to. It's behavior is called Pattern Matching. What it does is to try to make the statement true and the simplest example is <span style="font-weight: bold;"><em>X = 1</em></span>. Here erlang finds that the only way to make the statement true is if the variable <span style="font-weight: bold;"><em>X</em></span> stores the value <span style="font-weight: bold;"><em>1</em></span>. Here we also see the difference in using tuples and lists. If we make the statement <span style="font-weight: bold;"><em>{error, ErrorCode, ErrorMessage} = {error, 404, "File Not Found"}</em></span> it will find that to make this statement true it has to assign the variable <span style="font-weight: bold;"><em>ErrorCode</em></span> to <span style="font-weight: bold;"><em>"404"</em></span> and <span style="font-weight: bold;"><em>ErrorMessage</em></span> to <span style="font-weight: bold;"><em>"File Not Found"</em></span>. Pretty nifty eh? With lists you can do things like <span style="font-weight: bold;"><em>[FirstElement|TheRest] = [1,2,3,4]</em></span>. Here the variable <span style="font-weight: bold;"><em>FirstElement</em></span> will become <span style="font-weight: bold;"><em>1</em></span> and <span style="font-weight: bold;"><em>TheRest</em></span> will become <span style="font-weight: bold;"><em>[2,3,4]</em></span>.</p><h3>Conclusion</h3><p>This is it for now. In the next article I will explain amongst other things modules and functions along with the real power of Erlang that lies in processes.</p><p>Or if you want to dive into actually learning Erlang I would recommend Kevin Smith's excellent screencast <a href="http://pragprog.com/screencasts/v-kserl/erlang-in-practice">Erlang in Practice</a>.</p><p> </p>]]></content></entry></feed>
