Thursday, 16 May 2013

A little python vs ruby

Just a little comparison of python vs ruby which nicely sums up why I prefer ruby to python.

Coming from a perl background, parsing strings and manipulating data structures is the bread and butter of sysadmin scripting. Here we're going to split a string, add to the array, then join into a string again.

First, in python:

a = "a b c".split()
>>> a
['a', 'b', 'c']
>>> len(a)
3
>>> a.append("d")
>>> ",".join(a)
'a,b,c,d'

Ok, fair enough I guess. Now lets look at ruby:

a = "a b c".split
=> ["a", "b", "c"] 
a.size
=> 3 
a.push "d" 
=> ["a", "b", "c", "d"] 
a.join "," 
=> "a,b,c,d" 

Notice the difference? I'll try to summarise it in text.

For python, we split the string to get an array. We then run a global method to find the size of the array. We then call a method on array to append the new element. Finally we run a join method on a string and pass it the array.

For ruby, we split the string to get an array. We then run a method on the array to get the size (.length would also have worked). We then run a method on the array to add the element. We then run a method on the array to join to get our final string.

To me ruby is far more consistent. I'm not saying python is a bad language, I just find ruby to be particularly enjoyable to use.

Criticisms, suggestions and improvements welcome :)