CSC/ECE 517 Fall 2009/wiki1a 11 rubyvspython
Ruby vs. Python
Introduction
Python and Ruby are amongst some of the most popular programming languages in use today. Although this page compares and contrasts the two languages, when compared to the other existing languages in the market today, Ruby and Python are almost similar and developed with the same overall goals. However, the differences that do exist have made these two languages the subject of debate between their users.
Brief Descriptions
Python
Python is a high-level programming language with a design philosophy that emphasizes code readability, clear syntax and its standard library is large and comprehensive. Its use of indentation as block delimiters is unusual among popular programming languages. Python supports multiple programming paradigms (primarily object-oriented, imperative, and functional), features a fully dynamic type system and automatic memory management and is often used as a scripting language [1].
Here's some sample python code: [2]
name = input('What is your name?\n') print('Hi, ' + name + '.')
Ruby
Ruby is a dynamic, general purpose object-oriented programming language developed and designed by Yukihiro "Matz" Matsumoto who wanted a scripting language that was more powerful than Perl, and more object-oriented than Python. Ruby supports multiple programming paradigms, including functional, object oriented, imperative and reflective. It also has a dynamic type system and automatic memory management; it is therefore similar in varying respects to Python [3].
Here's some sample ruby code: [4]
puts "What is your name?" $name = STDIN.gets puts "Hi " + $name
Feature Comparison
There are a lot of features that Ruby and Python have in common. So before we compare their differences, its a good idea to list their common features:
- High-level programming languages (language with strong abstraction from the details of the computer [5]).
- Everything is an object, and variables are just references to objects [6].
- Fully dynamic type system
- A language is dynamically typed when majority of its type checking is performed at run-time as opposed to at compile-time [7].
- Both provide an interactive prompt [6].
- Automatic memory management
- In computer science, garbage collection is a form of automatic memory management. The garbage collector attempts to reclaim garbage, or memory used by objects that are no longer in use by the application [8].
Now, let us see how these two languages differ in their features:
For a brief summary of differences, see table below.
Strings in Python vs. Strings in Ruby
String objects in Python are immutable whereas in Ruby strings are mutable objects [9].
An immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created. If an object is known to be immutable, it can be copied simply by making a copy of a reference to it instead of copying the entire object. Because a reference is usually much smaller than the object itself, this results in memory savings and a boost in execution speed [10].
So in Python, adding a string to another can create several unwanted intermediate strings and consume memory. In Ruby however, strings can expand as required without consuming much memory or time [9].
Defining Private Variables and Methods
In Python "_" is appended in front of a variable or method name to make it private.
In Ruby, all variables defined in a class are by default private and no specific keyword is required to make them so. For making a method private, a method private is called just before the actual method.
private def sample_method_name
[11]
Code Blocks vs. Lambdas
In Ruby, a code block is an object which contains certain code along with a context required to execute it. A code block can be thought of as a function not bound to a name. This is one of the most distinctive and unique features in Ruby. A code block in Ruby is defined as follows [12]:
[1,2,3].each { |i| puts i}
In Python, the concept of code blocks does not exist but the ability of creating unnamed functions can be achieved using lambdas. The lambda function acts like any standard function in Python. A lambda may be used as follows [13]:
>>> (lambda x: x*2)(3) 8
Functions and Methods
There are no functions and methods separately in Ruby; all of them are methods.
string = 'Hello world' puts string.count('o'), string.length # prints 2, 11
In Python, for example, len() is a function, but items() is a method.
string = 'Hello world' print string.count('o'), len(string) # prints 2, 11
In Python, one needs to write self as the first parameter of a method definition. In Ruby, self is automatically available in a similar fashion as this in C++ [11].
Multiple Inheritance
Multiple inheritance refers to a feature of some object-oriented programming languages in which a class can inherit behaviors and features from more than one superclass. This contrasts with single inheritance, where a class may inherit from at most one superclass [14].
Python offers support for multiple inheritance and a class definition with multiple base classes looks like this [15]:
class DerivedClassName(Base1, Base2, Base3): <statement-1> . . . <statement-N>
Ruby does not support multiple inheritance but provides support so that classes can import modules as mixins [3]. A mixin is a class that provides a certain functionality to be inherited by a subclass, while not meant for instantiation (the generating of objects of that class). Inheriting from a mixin is not a form of specialization but is rather a means of collecting functionality. A class may inherit most or all of its functionality from one or more mixins through multiple inheritance [16].
require "tcalc" class Invoice include Tcalc # The line that mixes
[17]
Support for Threads
Ruby does not support OS (preemptive) threads and most code is not threadsafe.
Python does support preemptive OS threads which can be used to handle concurrency well when some threads are blocking on external sources (disk access, network IO, waiting on a socket, etc) [18].
Boolean Values
In Python you have a boolean data type called bool which is a subclass of int and which can either be True or False. Every Python object can either be True or False which is defined by overriding the __nonzero__ method of an object. By default all empty objects (empty lists, dictionaries, tuples, strings etc) are False. This also applies to 0 and 0.0 [19].
In Ruby the situation is completely different. There is no boolean data type but there are two singletons (true, instance of TrueClass and false, instance of FalseClass). Everything but nil and false is true. It's also not override-able [19].
Syntax Differences
- Unlike Python, in Ruby indentation is not significant.
- In Python, one has to write private instance variables using the long form self.__foobar. In Ruby, the form is @foobar.
- Ruby provides public, private, and protected to enforce access while Python uses underscore __convention__.
- Unlike Python, in Ruby parentheses for method calls are usually optional.
- Ruby uses elsif instead of elif as in Python.
- Ruby uses require instead of import as in Python. The usage however remains the same.
[6]
Summary of Differences
Python | Ruby | |
---|---|---|
Strings | Immutable | Mutable |
Private Variables | "_" is appended in front | private by default |
Private Methods | "_" is appended in front | method private called before actual method |
Code Blocks | Do not exist - Lambdas used instead. | Exist. |
Functions and Methods | Have a different significance | No difference |
Multiple Inheritance | Supported | Not Supported - uses mixins |
Threads | Supported | Not Supported |
Boolean Data Type | Supported | Not Supported |
Differences in (Web) Programming Environments
Web development in Ruby is done using the framework, Ruby on Rails. Ruby on Rails, often shortened to Rails or RoR, is an open source web application framework used with an Agile development methodology for rapid development. It uses the Model-View-Controller (MVC) architecture pattern to organize application programming [20]. Considered to be one of the best web development frameworks in the market, Ruby on Rails has helped to substantially increase the popularity of Ruby.
In the case of Python, there are several web development frameworks such as Django, Grok, Pylons, TurboGears, web2py, Zope [21]. Django is designed with a similar architecture and feature set as Rails to be just as efficient without being just a clone.
So while either frameworks may be used to develop a good web application, there are certain differences in both these frameworks [22]:
- Django has built in support for developer-friendly templates while Rails needs third party library support.
- Rails has in-built javascript support while Django has no direct support.
- In terms of Performance and Scalability, Django is considered better.
- Lesser number of plugins and support available for Django compared to Rails.
Rails has for some time retained the top position in the popularity charts with developers. However, the situation seems to be changing with Django beating Rails since 2008 [23].
Interesting Feature(s) Comparison: When is Python or Ruby preferred over the other
Python may be considered better than Ruby in the following cases [24]:
- Performance
- Ruby's interpreter performance trails compared to Python mainly due to the design of the interpreter. To execute Ruby code, the interpreter builds a syntax tree from the source code and then evaluates the syntax tree directly, instead of first compiling it into a more efficiently executable form.
- Threading
- Ruby's threading model has some inherent limitations which render it difficult to use or unsafe in some scenarios.
- Unicode
- Ruby does not yet have native support for Unicode or multibyte strings.
- Backward compatibility
- Ruby suffers from backward compatibility problems.
However, Ruby 2.0 aims to address all of the aforementioned problems.
Ruby may be considered better than Python in the following cases [25]:
- Ruby on Rails is considered on of the most efficient web development frameworks (see section 1.3 for details).
- Ruby provides mutable string support (see section 1.2.1 for more details).
- Ruby supports usage of constants [19].
Advantages Over Statically Typed Languages
A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time. Statically typed languages include Ada, C, C++, C#, JADE, Java, Fortran, Haskell, ML, Pascal, Perl and Scala [26].
Code Size
Python/Ruby are concise and compact as compared to Java which is verbose. This is shown in the example below:
Python
print "Hello, world!"
Java
public class HelloWorld { public static void main (String[] args) { System.out.println("Hello, world!"); } }
Static vs. Dynamic
In Python, you never declare anything. An assignment statement binds a name to an object, and the object can be of any type. If a name is assigned to an object of one type, it may later be assigned to an object of a different type. That's what it means to say that Python is a dynamically typed language. Python container objects (e.g. lists and dictionaries) can hold objects of any type, including numbers and lists. When you retrieve an object from a container, it remembers its type, so no casting is required [27].
In Java, all variable names (along with their types) must be explicitly declared. Attempting to assign an object of the wrong type to a variable name triggers a type exception. That's what it means to say that Java is a statically typed language. Java container objects (e.g. Vector and ArrayList) hold objects of the generic type Object, but cannot hold primitives such as int. To store an int in a Vector, you must first convert the int to an Integer. When you retrieve an object from a container, it doesn't remember its type, and must be explicitly cast to the desired type [27].
Flexibility
Flexibility of dynamically typed langauges such as Python and Ruby makes writing code significantly easier. Modules are easier to write, and easier to change. There are no build time issues at all [28].
- Java does not support operator overloading [29].
- Generators (functions that save state between different results) not present in Java [29].
- Ruby/Python support metaprogramming as well as the procedural and functional paradigms [30].
Comparison by Application Domains
Since Ruby and Python are almost similar languages built with the same broad goals, we cannot pin point on certain applications that may be built only in Python or Ruby. Yet, due to the certain differences that exist developers may prefer one over the other depending on the application's requirements.
As Rails is one of the most popular web development frameworks, it can be said that Ruby is more popular for web development that Python. Ruby on Rails makes a great framework to develop both small as well as high traffic sites. Ruby is, at present, exceptionally good at one specific kind of small project: database-backed web applications. Ruby on Rails counteracts all of Ruby's small-project disadvantages [31].
Some of the top organizations using Ruby on Rails include NASA, Motorola, Google, Amazon, Cisco, IBM, Oracle, Yahoo [32][33].
Python is better suited to desktop apps on Linux because you can perhaps integrate better to the host platform [34]. Python is believed to give better performance than Ruby and has a large standard library which is why more developers prefer it for areas such as text and numerical processing, operating system interfaces, internet protocols, internet security, software engineering, graphic design. Some of the big companies using Python include Google, Yahoo, CERN and NASA [35][36][1].
References
[1] http://en.wikipedia.org/wiki/Python_%28programming_language%29
[2] http://wiki.python.org/moin/SimplePrograms
[3] http://en.wikipedia.org/wiki/Ruby_%28programming_language%29
[4] http://www.fincher.org/tips/Languages/Ruby/
[5] http://en.wikipedia.org/wiki/High-level_programming_language
[6] http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/
[7] http://en.wikipedia.org/wiki/Type_system#Dynamic_typing
[8] http://en.wikipedia.org/wiki/Automatic_memory_management
[9] http://oreilly.com/catalog/9780596523695/
[10] http://en.wikipedia.org/wiki/Immutable_object
[11] http://johan.kiviniemi.name/blag/ruby-vs-python
[12] http://www.devarticles.com/c/a/Ruby-on-Rails/Code-Blocks-and-Iteration/
[13] http://www.secnetix.de/olli/Python/lambda_functions.hawk
[14] http://en.wikipedia.org/wiki/Multiple_inheritance
[15] http://docs.python.org/tutorial/classes.html
[16] http://en.wikipedia.org/wiki/Mixin
[17] http://www.wellho.net/resources/ex.php4?item=r119/mixdem.rb
[18] http://blog.ianbicking.org/ruby-python-power.html
[19] http://dev.pocoo.org/~mitsuhiko/pythonruby.html
[20] http://en.wikipedia.org/wiki/Ruby_on_Rails
[21] http://wiki.python.org/moin/WebFrameworks
[22] http://3columns.net/habitual/docs/RailsVsDjango.pdf
[23] www.venturedig.com/wordpress/wp-content/uploads/2009/04/django-vs-rails11.jpg
[24] http://en.wikipedia.org/wiki/Ruby_MRI#Criticism
[25] Ruby Cookbook: Recipes for Object Oriented Scripting : ISBN 10: 0-596-52369-6 | ISBN 13: 9780596523695
[26] http://en.wikipedia.org/wiki/Type_system
[27] http://www.ferg.org/projects/python_java_side-by-side.html
[28] http://www.artima.com/weblogs/viewpost.jsp?thread=4639
[29] http://www.razorvine.net/python/PythonComparedToJava
[30] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html
[31] http://www.infoq.com/news/2007/06/rubyvsjava
[32] http://www.ruby-lang.org/en/documentation/success-stories/
[33] http://blog.obiefernandez.com/content/2008/03/big-name-compan.html
[34] http://ubuntuforums.org/showthread.php?t=845563
[35] http://ubuntuforums.org/archive/index.php/t-416082.html
[36] http://www.python.org/doc/faq/general