Month: September 2009

Ruby versus Python

Posted by – 26/09/2009

This is not another rant to praise one in spite of the other (an everybody knows I love Ruby, so it would not be impartial), but sometimes people seems to live in another world and do things for the wrong reasons.

I just read this blog post by Kanwei Li in which he gives 2 or 3 reasons he ditched Ruby in favor of Python. First of all, both are great languages and, although I favor Ruby, I use Python for some projects and they are not all that different. Of course, everyone is free to choose which language one favors, but Kanwei seems to be “ditching” Ruby out of not knowing much about it, or out of preferring one style over the other…

His first “reason” is that in Python white spaces matter. I used to think this is just a matter of style, but every now and then mandatory alignment hurts me (just try to put together a code generator and you’ll notice it). Although my code is always correctly aligned, I like that it’s done so because I want it that way, and not because some language demands it. Rants and more rants have been written about Python’s mandatory alignment (or other languages lack of it), and I am not going through all of it… Just I don’t think it’s a good reason to ditch Ruby…

After, he makes a big deal out of Ruby’s ternary if. As written by him, he prefers

#python
if len(a) > 0:
        v = a[0]
        a = a[1:]
else:
        v = None

over Ruby’s ternary if

#ruby
v = a.empty? ? a.shift : nil

Hey! Come on… Ruby’s ternary if is not mandatory… It was copied from C just as a syntax sugar. You can do without it, just as in Python:

#ruby
if ! a.empty?
    v = a.shift
else
    v = nil
end

Better yet! you can use if’s return as v value:

#ruby
v = if ! a.empty?
    a.shift
else
    nil
end

How beautiful is that!

Python lacked ternary if for a long time, and when it finally acquired one via PEP 308 its syntax was made different from every other language! Although I don’t think that is a problem, some people might think it would be better not reinventing the wheel.

Next, Kanwei goes over a famous “problem” of Ruby: the lack of a sum method for Array. I admit it’s strange, but that is completely coherent: Ruby’s Arrays are ordered collection of objects and not mathematical arrays. How do you sum objects that are not numbers? Many different people will have many different answers to that, so Ruby leaves this decision for the programmer and provides basic methods to deal with collections of anything (that can be used to apply sum to numbers, if wished). So, in Ruby you have to use Array#inject to perform a sum:

[1,2,3].inject(0) { |sum, value| sum + value }

Array#inject (actually Enumerable#inject) was borrowed from Smalltalk and allows you to loop through an array, building up an “accumulator value” as you go. When it‚Äôs done, the final value of this accumulator is returned. Very useful for combining array elements, whether by summing them, building up a pretty display string, whatever. In the example above, I am initializing the accumulator with 0.

If you use Array to mathematical operations and you want your arrays to work that way, you can always add a sum method to Array class:

class Array
    def sum
        self.inject(0) {|sum, value| sum + value}
    end
end

Maybe it would be better if you just use Arrays as containers (as it was intended to) and implement that sum inside your own class… I completely agree with Reg Braithwaite here.

Kanwei also mention Python is faster than Ruby. That is true, but was “more true” some time ago. First of all, Python is older and has had more time to improve its speed. Ruby, ITOH, just now acquired a good VM and improvements to it finally can run parallel to improvements in the language itself, so I am expecting this to be less true every release. Python is already not getting much faster between releases, unlike Ruby (the differences between 1.8.7 and 1.9.1 are really impressive!). IMHO this is not a good reason to choose one instead of the other: if you really need speed, go for C ūüôā

Now this is something I find interesting Kanwei has mentioned: “Python is more production ready”. He argues that Google is using it, so it must be good. Well… I cannot argue against that: Google is really using Python. But IBM, Oracle, EA, Cisco, Siemens, etc are using Ruby… so that is just a matter of preferring one or another company. Both are production ready… I agree, though, that Ruby 1.9.1 has many differences from 1.8.7, and that that may be seen as some inconsistency, but Python also has changed a lot since its 2.0 version, for that matter. And the changes to Ruby brought many benefits… I think they worth it.

At last, Kanwei compares Python and Ruby docstrings. Here I also have to agree with him: Ruby docstrings sucks. Actually that’s why everybody uses rdoc instead (and that is much more powerful than Python’s docstrings). Again, I don’t think that is reason enough to ditch Ruby (actually, the existence of rdoc, rubygems & friends should bring people to Ruby instead), but that is a matter of personal taste.

Surely, Kanwei’s reasons were easy to argue against. There are areas were Python shines much more than Ruby (and vice-versa), but those Kanwei mentioned are not among them.

I think both languages are powerful enough, and both are way better than Perl or PHP, so either one you choose would be fine. Better if you don’t have to choose and use both ;). If you have to, ITOH, pay more attention on how you feel while coding in each one, and not to some cheap reasons such as above. If you are a programmer, what matters most is that you’ll spend a lot of time coding with any given language… let that be something pleasant then.

Good reading: Empire Rising by Sam Barone

Posted by – 13/09/2009

I usually don’t write about this, but along with technical and medicine books, I am always reading some fiction book. It began as an habit (every night I read some pages) when I was a teenager and now it became an addiction. I am always looking for good fiction books to read.

About 3 months ago I bought a pocket book (Dawn of Empire) by a first-time author (Sam Barone), and found it such a good story that I finished it in about a week and began looking for the sequence (Empire Rising). The story is about the dawn of civilization in Mesopotamia, and how humans left their days as nomadic tribes/clans in order to build villages and farms, and all the challenges that such a change brings along with it (including building and maintaining empires).

It took until last week for my favorite bookstore to get Empire Rising to me, and I almost finished it already. So far I have to say it is even better than the first one!

So this is for the fiction books fans: get these two books at once! It’s amazing how a first-time author managed to write such great books. Sam Barone is really someone to keep an eye on. I am already looking forward his next books.

Code testing coverage

Posted by – 10/09/2009

I like building tests for my code. That is not an old habit, it’s just something I’ve been developing in the recent months or some few years. No, I am not doing TDD (although that doesn’t sound like a bad idea): I just build tests after I code as a safeguard – to be sure I haven’t broken anything. I suspect there are more programmers like myself than those using tests as part of a TDD (BDD, SDD, etc) approach, but that is just an opinion.

Well I just recently became found of code coverage estimates and tools, and rcov is such a nice tool that sometimes I just find myself building tests just to “please” it. I also suspect there are at least a bunch of people that do the same. Here are the results of the test coverage of one of my projects:

spectra@rohan:~/work/xmpp4r-observable$ rake rcov
(in /home/spectra/work/xmpp4r-observable)
rm -r coverage
Loaded suite /usr/bin/rcov
Started
........................
Finished in 70.995814 seconds.
 
24 tests, 97 assertions, 0 failures, 0 errors
+----------------------------------------------------+-------+-------+--------+
|                  File                              | Lines |  LOC  |  COV   |
+----------------------------------------------------+-------+-------+--------+
|lib/xmpp4r-observable.rb                            |   648 |   414 |  61.4% |
|lib/thread_store.rb                                 |    58 |    39 |  87.2% |
|lib/observable_thing.rb                             |   187 |   118 |  91.5% |
+----------------------------------------------------+-------+-------+--------+
|Total                                               |   893 |   571 |  69.4% |
+----------------------------------------------------+-------+-------+--------+
69.4%   3 file(s)   893 Lines   571 LOC
spectra@rohan:~/work/xmpp4r-observable$

Sure it’s tempting to get more of lib/xmpp4r-observable.rb covered, isn’t it?

Apresentando XMPP4R-Observable

Posted by – 08/09/2009

H√° apenas alguns dias fiz uma apresenta√ß√£o no FISL10 sobre a utiliza√ß√£o de XMPP PubSub com Ruby e sobre um fork de uma biblioteca popular à qual acrescentei os rudimentos do PubSub. Naquela mesma apresenta√ß√£o listei uma s√©rie de problemas que aquela abordagem tem e falei sobre um roadmap para o futuro…

Acontece que acabei me convencendo de que n√£o posso utilizar o PubSub no lado XMPP da biblioteca e uma forma de periodical pooling no lado Ruby. Resolvi, ent√£o, substituir a biblioteca que havia forkado por uma vers√£o Observable, preservando as coisas boas do XMPP4R-Simple. O resultado chamei de XMPP4R-Observable, e acabo de publicar no GitHub.

Uma boa parte do c√≥digo est√° coberta por testes (e “roubei” alguns dos testes da pr√≥pria XMPP4R-Simple)… pretendo cobrir o restante ao longo do tempo (contribui√ß√Ķes s√£o bem-vindas). Por hora, chamei esse primeiro release de vers√£o 0.5.1 e acrescentei um .gemspec para gerar um .gem automaticamente… No entanto, o GitHub ainda n√£o publicou o .gem… Quando publicar, para instal√°-lo deve ser t√£o simples quanto:

bash# gem sources -a http://gems.github.com
bash# gem install spectra-xmpp4r-observable

N√£o deixem de reportar qualquer erro. Happy hacking.

Update 2009-09-13 10:29:00: Acabo de confirmar que o .gem foi publicado pelo GitHub.

Update 2009-10-10 20:21:00: O .gem do XMPP4R-Observable vai ser mantido no GemCutter, a partir de hoje.

EeePC: Surviving liquid spills – phase II

Posted by – 03/09/2009

About four months ago I described how my EeePC survived the spilling of orange juice over its keyboard. No! I never spilled anything on it again, if that’s what you’re thinking… But I noticed that some keys (those that got more juice on) began to malfunction. At the beginning I paid no attention to it, hoping that it would just go away, but, eventually, they just stop working… And those are not just unimportant keys… I am talking about arrows and the forward-slash (/) keys in the lower right corner of the keyboard!!! How could I survive without those keys, without a quick access to my bash history and vim search?

Well, I began googling around and found some good advice. Everything that made sense regarding how to cleanup my keyboard I compiled and, when I was enough confident it would work, I just follow the procedure I’ve devised. This is what I did:

  1. After turning it off and removing the battery, I removed the keyboard. Check the instructions I linked in my previous article for some pictures on how to do it.
  2. I poured 500 mL of distilled water in a clean plastic box (I bought 1L for BRL 20 at a local pharmacy), added enough dish detergent to make some foam (I was careful to select a non-biodegradable one) and drowned the whole keyboard in the solution.
  3. For the next 30 minutes I pressed and released the affected keys over and over again. My intention was to dissolve anything that might have remained from the orange juice.
  4. I left it soaking in the solution for the next 12 hours.
  5. The next day I got the keyboard out of the solution and used current tap water to remove any detergent still left in it. This might have took about 10 minutes.
  6. Our tap water is really clean, but its hard, and I would not like to remove any juice from the keyboard just to add some minerals that might have the same effect, so after I was certain all the detergent was removed, I left the keyboard in the remaining of the distilled water for another 12 hour soak.
  7. After that I just removed the keyboard from the soak, dried it a little bit using a paper towel and left it to air-dry (away from the sun). I don’t remember how long it took, but I believe not more than 4 hours… Those were hot days… Anyway, I was really sure it was dry.

When I plugged it back, surprise! All keys are working again! Of course, that was just what worked for me… Best advice still is: Keep liquids away your EeePC!

Caverna do Dragão

Posted by – 01/09/2009

Uma das coisas que fiz nas minhas f√©rias foi ler o roteiro do √ļltimo epis√≥dio de “Caverna do Drag√£o” (Dungeons & Dragons para os angl√≥fonos), um desenho animado dos anos 80 que fez a festa dos que eram crian√ßas na √©poca (eu inclusive) e dos que jogavam RPG (novamente, eu inclusive).

Eu tinha ouvido diversas teorias sobre o que representava o Realm da Caverna do Drag√£o, e o que as crian√ßas estavam fazendo l√°… algumas bastante fantasiosas, mas devo admitir que o roteiro real √© bem mais interessante do que todas as teorias paralelas. Quem quiser dar uma olhada, o original em ingl√™s est√° no site do roteirista (eu tamb√©m achei uma tradu√ß√£o para o portugu√™s). N√£o vou estragar a festa de ningu√©m adiantando o final, mas tenho certeza que voc√™s v√£o gostar.

Pena que n√£o produziram o √ļltimo epis√≥dio… Realmente seria um belo encerramento para a s√©rie animada… Dei uma procurada por a√≠ e n√£o me aguentei: acabei comprando o pacote com os 5 DVDs da s√©rie… Agora √© s√≥ aguardar a chegada…