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

From Expertiza_Wiki
Jump to navigation Jump to search
Line 164: Line 164:
[[Image:django-vs-rails.jpg]]
[[Image:django-vs-rails.jpg]]


==Interesting Features Comparison==
==Interesting Feature(s) Comparison: When is Python or Ruby better than 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 [http://en.wikipedia.org/wiki/Ruby_MRI#Criticism]:
* 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 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:
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?
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.
[http://www.b-list.org/weblog/2006/jun/18/lets-talk-about-python-and-ruby/]


 
Ruby may be considered better than Python in the following cases [Ruby Cookbook]:
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.
* Ruby on Rails is considered on of the most efficient web development frameworks (see section 1.3 for details).
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).
* Ruby provides mutable string support (see section 1.2.1 for more details).
[http://blog.ianbicking.org/ruby-python-power.html]
* Ruby supports usage of constants [http://dev.pocoo.org/~mitsuhiko/pythonruby.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==

Revision as of 20:59, 7 September 2009

Ruby vs. Python

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.

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, 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. [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 [8]
  • 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. [9]


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. [10]

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. [11]

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. [12]

Defining Private Variables and Methods

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.

private
  def sample_method_name

[13]

Lambdas vs. Code Blocks

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 [14]:

[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 [15]:

>>> (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++. [16]

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. [17]

Python offers support for multiple inheritance and a class definition with multiple base classes looks like this [18]:

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. [19] 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. [20]

require "tcalc"
class Invoice
  include Tcalc    # The line that mixes

[21]

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). [22]

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 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. [23]

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.
  • 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 require instead of import as in Python. The usage however remains the same.

[24]

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


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 [25]. 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 [26]. 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 [www.3columns.net/habitual/docs/RailsVsDjango.pdf]:

  • 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. [27]

Interesting Feature(s) Comparison: When is Python or Ruby better than the other

Python may be considered better than Ruby in the following cases [28]:

  • 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 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 [Ruby Cookbook]:

  • 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 [29].

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.[30]

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

Concise and compact vs. verbose

Python

print "Hello, world!"

Java

public class HelloWorld
{
   public static void main (String[] args)
   {
       System.out.println("Hello, world!");
   }
}

flexibility

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. [31]

  • java does not support operator overloading
  • 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

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.

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. [32]

Some of the top organizations using Ruby on Rails include NASA, Motorola, Google, Amazon, Cisco, IBM, Oracle, Yahoo. [33] [34]

Python is better suited to desktop apps on Linux because you can perhaps integrate better to the host platform. [35]

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. [36] [37] [38]


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.