Are you looking for my non-technical blog?

This is now my technical-only blog, my non-technical blog is here.

17 February 2012

Python vs Ruby - String to Integer

I'm a big Python fan, but recently, I decided to have a look at Ruby. I'm still not that qualified to do a comparison between the two languages, so let me instead take a snapshot from each of them and do a quick comparison based on it, and based on my own understanding of each.

Both languages have their ways to transform a strings with integers in there into integers.

In Python:
>>> int("33")
>>> int("33 + 3")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '33 + 3'
>>> int("Three")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Three'

In Ruby:
irb(main):007:0> "33".to_i
=> 33
irb(main):008:0> "33 + 3".to_i
=> 33
irb(main):009:0> "Three".to_i
=> 0

So first of all, Ruby seems to be more strictly Object Oriented language, than Python. Sure, Python treats everything as an Object too, a String or an Integer are objects in both languages and they have their own properties and methods, which is not the case with C for example, however I see here that Python uses a built-in methods, while Ruby - which also has its built-in methods - yet it tended more to do the transformation here the object way. 

Python prefers to have one - and preferably only one - obvious way to do things, hence when I typed stings composed of stuff other then integers it returned an error. It tends to make it easier for programmers to predict the result. While in Ruby, the result wasn't that obvious, it tried not to return an error and decided to think in an work-around for me me, on the second line it just took the integer part at the beginning of the string then ignored the rest of it, while in the third line it returned zero. At the end of the day, this is a matter of taste, some people might like the Python way of keeping everything predictable, while some others might like the Ruby easy-goingness and not nagging and returning errors to them all the time.

No comments:

Post a Comment