CSC/ECE 517 Fall 2009/wiki1a 11 rubyvspython: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
 
(41 intermediate revisions by 3 users not shown)
Line 2: Line 2:


==Introduction==
==Introduction==
Python and Ruby are amongst some of the most popular programming languages in use today. Although this pages 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.  
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===
===Brief Descriptions===


====Python====
====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. [http://en.wikipedia.org/wiki/Python_%28programming_language%29]
Python is a [http://en.wikipedia.org/wiki/High-level_programming_language 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, [http://en.wikipedia.org/wiki/Imperative_programming imperative], and functional), features a fully [http://en.wikipedia.org/wiki/Type_system#Dynamic_typing dynamic] type system and [http://en.wikipedia.org/wiki/Memory_management automatic memory management] and is often used as a scripting language [1].


Here's some sample python code: [http://wiki.python.org/moin/SimplePrograms]
Here's some sample python code: [2]
  name = input('What is your name?\n')
  name = input('What is your name?\n')
  print('Hi, ' + name + '.')
  print('Hi, ' + name + '.')


====Ruby====
====Ruby====
Ruby is a dynamic, reflective, 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. [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29]
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 [http://en.wikipedia.org/wiki/Reflection_(computer_science) 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: [http://www.fincher.org/tips/Languages/Ruby/]
Here's some sample ruby code: [4]
  puts "What is your name?"
  puts "What is your name?"
  $name = STDIN.gets
  $name = STDIN.gets
  puts "Hi " + $name
  puts "Hi " + $name


==Feature Comparison==
==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:
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 [http://en.wikipedia.org/wiki/High-level_programming_language])
* 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. [http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/]
* Everything is an object, and variables are just references to objects [6].
* Fully dynamic type system
* 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.[http://en.wikipedia.org/wiki/Type_system#Dynamic_typing]
: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 [http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/]
* Both provide an interactive prompt [6].
* Automatic memory management
* Automatic memory management
:In computer science, garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory used by objects that are no longer in use by the application. [http://en.wikipedia.org/wiki/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:
Now, let us see how these two languages differ in their features:


''For a brief summary of differences, see table below.''
''For a brief summary of differences, see [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2009/wiki1a_11_rubyvspython#Summary_of_Differences table] below.''


====Strings in Python vs. Strings in Ruby====
====Strings in Python vs. Strings in Ruby====
String objects in Python are immutable whereas in Ruby strings are mutable objects. [http://oreilly.com/catalog/9780596523695/]
String objects in Python are [http://en.wikipedia.org/wiki/Mutable 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. [http://en.wikipedia.org/wiki/Immutable_object]
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. [http://oreilly.com/catalog/9780596523695/]  
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====  
====Defining Private Variables and Methods====  
In Python "_" is appended in front of a variable or method name to make it private.  
In Python "_" is appended in front of a variable or method name to make it private.  


In Ruby, all variable 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.
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
  private
   def sample_method_name
   def sample_method_name
[http://johan.kiviniemi.name/blag/ruby-vs-python]
[11]


====Lambdas vs. Code Blocks====
====Code Blocks vs. Lambdas====
In Ruby, a code block is an object which is 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 [http://www.devarticles.com/c/a/Ruby-on-Rails/Code-Blocks-and-Iteration/]:
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}
  [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 [http://www.secnetix.de/olli/Python/lambda_functions.hawk]:
In Python, the concept of code blocks does not exist but the ability of creating unnamed functions can be achieved using [http://www.secnetix.de/olli/Python/lambda_functions.hawk lambdas]. The lambda function acts like any standard function in Python. A lambda may be used as follows [13]:
  >>> (lambda x: x*2)(3)
  >>> (lambda x: x*2)(3)
  8  
  8
 
====Functions and Methods====  
====Functions and Methods====  
There are no functions and methods separately in Ruby; all of them are methods.  
There are no functions and methods separately in Ruby; all of them are methods.  
Line 69: Line 68:
  print string.count('o'), len(string)  # prints 2, 11
  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++. [http://johan.kiviniemi.name/blag/ruby-vs-python/]
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====
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. [http://en.wikipedia.org/wiki/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 [http://en.wikipedia.org/wiki/Superclass_(computer_science) 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 [http://docs.python.org/tutorial/classes.html]:
Python offers support for multiple inheritance and a class definition with multiple base classes looks like this [15]:
  class DerivedClassName(Base1, Base2, Base3):
  class DerivedClassName(Base1, Base2, Base3):
     <statement-1>
     <statement-1>
Line 82: Line 81:
     <statement-N>
     <statement-N>


Ruby does not support multiple inheritance but provides support so that classes can import modules as mixins. [http://en.wikipedia.org/wiki/Ruby_(programming_language)]
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. [http://en.wikipedia.org/wiki/Mixin]
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 [http://docs.oasis-open.org/dita/v1.0/archspec/specialize.html 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"
  require "tcalc"
  class Invoice
  class Invoice
   include Tcalc    # The line that mixes
   include Tcalc    # The line that mixes
[http://www.wellho.net/resources/ex.php4?item=r119/mixdem.rb]
[17]


====Support for Threads====  
====Support for Threads====  
Ruby does not support OS (preemptive) threads and most code is not threadsafe.  
Ruby does not support OS (preemptive) threads and most code is not [http://en.wikipedia.org/wiki/Thread_safety 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).
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].
[http://blog.ianbicking.org/ruby-python-power.html]


====Boolean Values====  
====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, dicts, tuples, strings etc) are False. This also applies to 0 and 0.0.
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.
In Ruby the situation is completely different. There is no boolean data type but there are two [http://msdn.microsoft.com/en-us/library/ms998426.aspx singletons] (true, instance of TrueClass and false, instance of FalseClass). Everything but nil and false is true. It's also not override-able [19].
[http://dev.pocoo.org/~mitsuhiko/pythonruby.html]


====Syntax Differences====  
====Syntax Differences====  
Line 106: Line 103:
* Ruby provides public, private, and protected to enforce access while Python uses underscore __convention__.
* 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.
* Unlike Python, in Ruby parentheses for method calls are usually optional.
* In Ruby there is true and false instead of True and False (and nil instead of None) as compared to Python.
* Ruby uses ''elsif'' instead of ''elif'' as in Python.
* Ruby uses ''elsif'' instead of ''elif'' as in Python.
* Ruby uses ''require'' instead of ''import'' as in Python. The usage however remains the same.
* Ruby uses ''require'' instead of ''import'' as in Python. The usage however remains the same.
[http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/]
[6]


====Summary of Differences====
====Summary of Differences====
Line 142: Line 138:


! Threads
! Threads
| Supported || Not Supported
|-
! Boolean Data Type
| Supported || Not Supported
| Supported || Not Supported
|-
|-
Line 147: Line 147:
|}
|}


<br />


==Differences in (Web) Programming Environments==
==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.[http://en.wikipedia.org/wiki/Ruby_on_Rails] 
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 [http://en.wikipedia.org/wiki/Agile_software_development Agile] development methodology for rapid development. It uses the [http://en.wikipedia.org/wiki/Model-view-controller 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.
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.[http://wiki.python.org/moin/WebFrameworks]
In the case of Python, there are several web development frameworks such as [http://www.djangoproject.com/ Django], [http://grok.zope.org/ Grok], [http://pylonshq.com/ Pylons], [http://turbogears.org/ TurboGears], [http://www.web2py.com/ web2py], [http://www.zope.org/ Zope] [21]. Django is designed with a similar architecture and feature set as Rails to be just as efficient without being just a clone.  
Django is designed with a similar architecture and feature set to 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 [3columns.net/habitual/docs/RailsVsDjango.pdf]:
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.
* 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.
* Rails has in-built javascript support while Django has no direct support.
* In terms of Performance and scalability, Django is considered better.
* In terms of Performance and Scalability, Django is considered better.
* Lesser number of plugins and support available for Django compared to Rails.
* 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.
 
[http://venturedig.com/wordpress/wp-content/uploads/2009/04/django-vs-rails11.jpg Django vs. 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].


[[Image:django-vs-rails.jpg]]
[[Image:django-vs-rails.jpg]]


==Interesting Features Comparison==
==Interesting Feature(s) Comparison: When is Python or Ruby preferred over the other==
Ruby better for:
* mutable strings!
* support for constants
http://dev.pocoo.org/~mitsuhiko/pythonruby.html


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 [http://en.wikipedia.org/wiki/Abstract_syntax_tree 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.


would lead me to Python over Ruby:
Ruby may be considered better than Python in the following cases [25]:
1. Mutable built-in types, which are problematic for two reasons. One is that using them absolutely destroys the portability of a piece of code and makes it not Play Nice with any other components you happen to be using. The other is that it feels like the wrong solution: you’ve got an OO language, so when you want something that behaves like one of the built-ins most of the time but has this or that or the other extra thing, why not subclass it?
* Ruby on Rails is considered on of the most efficient web development frameworks (see section 1.3 for details).
2. Just mentioning a method’s name calls it. This makes it extremely cumbersome to really do higher-order programming, and can be counterintuitive and confusing. Let me talk about the method, pass it around, bind it to other names, and not actually call it until I’m good and ready.
* Ruby provides mutable string support (see section 1.2.1 for more details).
[http://www.b-list.org/weblog/2006/jun/18/lets-talk-about-python-and-ruby/]
* Ruby supports usage of constants [19].
 
 
Ruby, to my knowledge, does not support OS (preemptive) threads, or if it does it is buggy (or "experimental") and most code is not threadsafe.
Python does support preemptive OS threads. Python OS-level threads can be used to handle concurrency well when some threads are blocking on external sources (disk access, network IO, waiting on a socket, etc).
[http://blog.ianbicking.org/ruby-python-power.html]
 
 
[http://blog.ianbicking.org/ruby-python-power.html]
What's better in Python?
There are a few libraries that I think are notable for Python, because they address core programming techniques; things that might be language extensions in other, less dynamic languages. They are also notable because they aren't part of the Python core, for better or worse. In many cases Ruby equivalents exist, but may not be as mature (most of the reference projects have been in development in Python for many years).
    * Formal interfaces (Zope and PyProtocols); both also include the adaptation of objects. Ruby work on the same ideas is happening in ruby-contract
    * Generic functions (another take on the issues of adaptation)
    * Pyrex and ctypes for integration with external libraries (both languages support SWIG well)
    * py2exe and py2app for distribution of complete applications (both languages are ameniable to normal distribution methods on Unixy systems). Ruby modules to do the same sorts of things is happening in rubyscript2exe and Exerb
    * Numarray and scipy for dealing efficiently with large (typically homogeneous) datasets. Ruby work on this is happening in sciruby and Numerical Ruby
    * Psyco for various runtime optimizations (note that there is lots of ongoing performance-related work in both languages; Psyco is notable because it is very usable right now)
 
What's better in Ruby?
I'm not that familiar with Ruby libraries, but I get the impression that like Python the Next Step for Ruby will be accomplished on top of the language, not as an extension to it. If you know of something that belongs here, please comment. (Note: I'm not including tool-like libraries or application frameworks in these lists -- that way lies aesthetics; a valid thing to argue over, but not here please.)
    * gems for packaging of libraries (setuptools is trying to address this issue in Python). distutils is a little more self-contained for compiling C code.
    * rdoc is their standard documentation extractor/generator. Python has these, but no real accepted default generator.
 
 
[http://en.wikipedia.org/wiki/Ruby_MRI#Criticism]
Version 1.8, the current stable version of the interpreter, has some limitations, which include:
    * Performance -- the Ruby interpreter's performance trails that of comparable languages such as Perl, PHP, and Python[5][6], 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 more efficiently executable form.
    * Threading -- the Ruby threading model uses green threads [7], and its model has some inherent limitations which render it difficult to use or unsafe in some scenarios.[8]
    * Unicode -- Ruby does not yet have native support for Unicode or multibyte strings.[9]
    * Backward compatibility -- Ruby suffers from backward compatibility problems.[10]
 
Ruby 2.0 aims to address all of the aforementioned problems:
    * Performance -- a new, faster interpreter, YARV, a virtual machine which executes bytecode instructions.
    * Threading -- native threads will be used instead of green threads.[11]
    * Unicode -- full support for Unicode strings.


==Advantages Over Statically Typed Languages==
==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.[http://en.wikipedia.org/wiki/Type_system]
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 [http://en.wikipedia.org/wiki/Ada_(programming_language) Ada], C, C++, C#, [http://en.wikipedia.org/wiki/JADE_(programming_language) JADE], Java, Fortran, [http://en.wikipedia.org/wiki/Haskell_(programming_language) Haskell], [http://en.wikipedia.org/wiki/ML_(programming_language) ML], Pascal, Perl and [http://en.wikipedia.org/wiki/Scala_(programming_language) Scala] [26].
 
====static vs. dynamic====
http://www.ferg.org/projects/python_java_side-by-side.html
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.
 
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.


====Code size====
====Code Size====
Concise and compact vs. verbose
Python/Ruby are concise and compact as compared to Java which is verbose. This is shown in the example below:
   
   
Python
Python
Line 236: Line 201:
  }
  }


====flexibility====
====Static vs. Dynamic====
flexibility of dynamically typed langauges makes writing code significantly easier. Modules are easier to write, and easier to change. There are no build time issues at all. [http://www.artima.com/weblogs/viewpost.jsp?thread=4639]
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].


* java does not support operator overloading
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].
* generators (functions that save state between different results) not present in Java
* supports metaprogramming as well as the procedural and functional paradigms.


==Comparison by Applications/Projects==
====Flexibility====
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 applications requirements.
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 [http://en.wikipedia.org/wiki/Metaprogramming metaprogramming] as well as the procedural and functional paradigms [30].


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. [http://www.infoq.com/news/2007/06/rubyvsjava]
==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.


Some of the top organizations using Ruby on Rails include NASA, Motorola, Google, Amazon, Cisco, IBM, Oracle, Yahoo.
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].
[http://www.ruby-lang.org/en/documentation/success-stories/]
[http://blog.obiefernandez.com/content/2008/03/big-name-compan.html]


Python is better suited to desktop apps on Linux because you can perhaps integrate better to the host platform. [http://ubuntuforums.org/showthread.php?t=845563]
Some of the top organizations using Ruby on Rails include NASA, Motorola, Google, Amazon, Cisco, IBM, Oracle, Yahoo [32][33].
 
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.
[http://ubuntuforums.org/archive/index.php/t-416082.html]
[http://www.python.org/doc/faq/general/]
[http://en.wikipedia.org/wiki/Python_(programming_language)]


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==
==References==
1. http://en.wikipedia.org/wiki/Python_%28programming_language%29
[1] http://en.wikipedia.org/wiki/Python_%28programming_language%29
 
<br>[2] http://wiki.python.org/moin/SimplePrograms
2. http://wiki.python.org/moin/SimplePrograms
<br>[3] http://en.wikipedia.org/wiki/Ruby_%28programming_language%29
 
<br>[4] http://www.fincher.org/tips/Languages/Ruby/
3. http://en.wikipedia.org/wiki/Ruby_%28programming_language%29
<br>[5] http://en.wikipedia.org/wiki/High-level_programming_language
 
<br>[6] http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/
4.
<br>[7] http://en.wikipedia.org/wiki/Type_system#Dynamic_typing
<br>[8] http://en.wikipedia.org/wiki/Automatic_memory_management
<br>[9] http://oreilly.com/catalog/9780596523695/
<br>[10] http://en.wikipedia.org/wiki/Immutable_object
<br>[11] http://johan.kiviniemi.name/blag/ruby-vs-python
<br>[12] http://www.devarticles.com/c/a/Ruby-on-Rails/Code-Blocks-and-Iteration/
<br>[13] http://www.secnetix.de/olli/Python/lambda_functions.hawk
<br>[14] http://en.wikipedia.org/wiki/Multiple_inheritance
<br>[15] http://docs.python.org/tutorial/classes.html
<br>[16] http://en.wikipedia.org/wiki/Mixin
<br>[17] http://www.wellho.net/resources/ex.php4?item=r119/mixdem.rb
<br>[18] http://blog.ianbicking.org/ruby-python-power.html
<br>[19] http://dev.pocoo.org/~mitsuhiko/pythonruby.html
<br>[20] http://en.wikipedia.org/wiki/Ruby_on_Rails
<br>[21] http://wiki.python.org/moin/WebFrameworks
<br>[22] http://3columns.net/habitual/docs/RailsVsDjango.pdf
<br>[23] www.venturedig.com/wordpress/wp-content/uploads/2009/04/django-vs-rails11.jpg
<br>[24] http://en.wikipedia.org/wiki/Ruby_MRI#Criticism
<br>[25] Ruby Cookbook: Recipes for Object Oriented Scripting : ISBN 10: 0-596-52369-6 | ISBN 13: 9780596523695
<br>[26] http://en.wikipedia.org/wiki/Type_system
<br>[27] http://www.ferg.org/projects/python_java_side-by-side.html
<br>[28] http://www.artima.com/weblogs/viewpost.jsp?thread=4639
<br>[29] http://www.razorvine.net/python/PythonComparedToJava
<br>[30] http://www.javaworld.com/javaworld/jw-07-2006/jw-0717-ruby.html
<br>[31] http://www.infoq.com/news/2007/06/rubyvsjava
<br>[32] http://www.ruby-lang.org/en/documentation/success-stories/
<br>[33] http://blog.obiefernandez.com/content/2008/03/big-name-compan.html
<br>[34] http://ubuntuforums.org/showthread.php?t=845563
<br>[35] http://ubuntuforums.org/archive/index.php/t-416082.html
<br>[36] http://www.python.org/doc/faq/general

Latest revision as of 22:31, 16 September 2009

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