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

From Expertiza_Wiki
Jump to navigation Jump to search
 
(65 intermediate revisions by 4 users not shown)
Line 3: Line 3:


   
   
==  <center> '''Ruby vs Python''' </center> ==
=  <center> '''Ruby vs Python''' </center> =


== Definition of Ruby and Python ==
== Definition of Ruby and Python ==




'''Ruby''' is a dynamic, reflective, general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features.
'''Ruby''' is a dynamic,interpreted language that includes a powerful set of libraries. While it is often referred to as a scripting language, it is a pure objected-oriented language that has sufficient expressiveness for general-purpose applications.It combines syntax inspired by Perl with Smalltalk-like features.


'''Python''' is an interpreted, object-oriented, high-level programming language with dynamic semantics.
'''Python''' is an object-oriented scripting language with dynamic semantics.Its design mixes software engineering features of traditional languages with the usability of scripting languages.


== Differences in their language features ==
== Differences in their language features ==
The first thing to be noted in Ruby is that in Ruby everything is an object, whereas in Python you have the liberty to code without using objects.  
1.The first thing to be noted in Ruby is that,everything is an object, whereas in Python we have the liberty to code without using objects.


// include example here
Ruby:String and numbers as objects
if x.between?(7,12) do ...


In ruby, the programmer can use blocks to extend the language for application specific control statements where as in Python you are supposed to use only the control statements provided by the language.
2.In ruby, the programmer can use blocks to extend the language for application specific control statements where as in Python we are supposed to use only the control statements provided by the language.


Ruby Blocks:
  def aliens
if block_given?
  i = 1
  j = 2
  yield(i, j)
  else puts “magick”
  end
end
aliens { |x, y| puts x }
aliens
In this case if the block is provided to the method, it executes the if statement, otherwise it executes the else statement
Python Control statements:
# Continue
nlist = []
for i in xrange(0,100):
    if i == 0:
        continue
    nlist.append( 7 / i )
# Break
# How many heads can we flip in a row?
heads = 0
while 1:
    if x = 0:
        break
    else:
        x = random.rand(0,1)
        heads += 1
# Pass
# If you don't want to do anything in a case
x = 0
while 1:
    if x <= 100:
        pass
    elif x = 101:
        print "Just enough Dalmations!"
    else:
        print "Argh!  Too many Dalmations!"
        break
    x += 1
3.Ruby protects class attributes.We can’t access attributes of objects from outside the class.
Python doesn’t protect our code from other programmers. If they want to shoot themselves in the foot they are allowed to do so.
Ruby code snippet without attributes:
  class Person
  def fname
    @fname
  end
  def fname=(fname)
    @fname = fname
  end
  def lname
    @lname
  end
  def lname=(lname)
    @lname = lname
  end
  end
Ruby code snippet with attributes:
class Person
  attr_accessor :fname, :lname
end
4.In Ruby, there are no functions, but there are methods, blocks and lambdas. All of them seem to have subtle differences, and sometimes we need to not just call them, but use .call().
In Python, there are only functions. Lambdas are functions whose name is <lambda>. Methods are functions that are wrapped, we don’t have to pass self.
Ruby Method:
class Boogy
def initialize
@dix = 15
end
def arbo
puts "#{@dix} ha\n"
end
end
b = Boogy.new # initializes an instance of Boogy
b.arbo # prints "15 ha"
Python Lambda:
def make_incrementor (n): return lambda x: x + n
f = make_incrementor(2)
g = make_incrementor(6)
print f(42), g(42)
gives output
44 48
5.The one line nameless mini-functions that can be created in Python are called Lambdas where as its Ruby counterpart is called as Blocks. Not only the name is different but also Blocks have some terrific advantage over lambdas. One of the most notable advantage is that Ruby blocks are more powerful, in that the interaction between the blocks and its contents is quite easy where as its almost impossible for the interaction between lambdas and its contents in Python. The other advantage is that Ruby blocks have access to the variables in the scope in which they were defined. This allows blocks to be used in a more expressive manner.
code snippet for computing the largest of two numbers using python lambdas
  >>>bigger = lambda a, b : a > b
  >>>print bigger(1,2)
  False
  >>>print bigger(2,1)
  True
code snippet for computing the square of each number in the array  using ruby blocks
  array = [1, 2, 3, 4]
  array.iterate! do |n|
  n ** 2
  end
  puts array.inspect
  # => [1, 4, 9, 16]
6.Python has a much greater range of libraries available to it, and most of those libraries are more mature and better documented than their Ruby counterparts.
Example of a python library : "all"
  def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
7.As far as readability is concerned, Python is considered to be easily readable whereas Ruby’s code is considered to be on the downside for readability.


== Differences in Programming Environment ==
== Differences in Programming Environment ==
Both Ruby and Python run on almost all the user friendly platforms like Windows9x/2000/NT, Unix, Mac-OS, MS-DOS. The difference in their programming environments is very subtle.


Python has a Virtual Machine which optimizes certain functions like hash functions and sorting algorithms.  
Python has a Virtual Machine which optimizes certain functions like hash functions and sorting algorithms.  


Ruby as such does not have any virtual machine but it acts as an interpreter. There is a project going on for building a virtual machine for Ruby- YARV [http://www.atdot.net/yarv/]
Ruby as such does not have any virtual machine but it acts as an interpreter. There is a project going on for building a virtual machine for Ruby- the YARV [http://www.atdot.net/yarv/].


== What Ruby has and Python does not have? ==
== What Ruby has and Python does not have? ==
Ruby has continuations, where as Python does not have it. One notable use of continuations in Ruby is for breakpoints in debuggers.  
Ruby has continuations, where as Python does not have it. One notable use of continuations in Ruby is for breakpoints in debuggers.  
a continuation is an abstract representation of the control state, of the things to come. Practically continuation support in a language means you can “save” your state at a point and return to it later. This is called a first-class continuation.
Continuation is an abstract representation of the control state, of the things to come. Practically continuation support in a language means we can “save” our state at a point and return to it later. This is called a first-class continuation.


In ruby, the callcc method is used (it’s Kernel#callcc) to create a Continuation class. Look at this small sample:
In ruby, the callcc method is used (it’s Kernel#callcc) to create a Continuation class. Look at this small sample:
Line 47: Line 179:
== What Python has and Ruby does not have? ==
== What Python has and Ruby does not have? ==


1. It’s worth mentioning here that Python has some big features that Ruby doesn’t, like for example list comprehensions.
1.It’s worth mentioning that Python has some big features like list comprehensions that Ruby doesn’t.


   [foo(x) for x in alist if bar(x) != 'frotz']
   [foo(x) for x in alist if bar(x) != 'frotz']
Line 57: Line 189:
   if bar(x) != 'frotz':
   if bar(x) != 'frotz':
   foo.append(x)
   foo.append(x)
2.
 
2.Python uses whitespace indentation, rather than curly braces or keywords, to delimit statement blocks (a feature also known as the off-side rule). An increase in indentation comes after certain statements; a decrease in indentation signifies the end of the current block.
 
Indented piece of Python code:
def perm(l):
        # Compute the list of all permutations of l
    if len(l) <= 1:
                  return [l]
    r = []
    for i in range(len(l)):
              s = l[:i] + l[i+1:]
              p = perm(s)
              for x in p:
              r.append(l[i:i+1] + x)
    return r


== Advantages over statically typed languages ==
== Advantages over statically typed languages ==
Line 107: Line 253:
prints the string 1 4 9 16 25; an iterator takes each element of the list and passes it into the code block as the variable n.
prints the string 1 4 9 16 25; an iterator takes each element of the list and passes it into the code block as the variable n.


== Projects better suited for Ruby  ==
== Comparison of Ruby and Python based on their Application ==


The most prominent application of Ruby is in web development using Ruby on Rails.
Ruby on Rails is an open source web framework. Rails was created by David Heinemeier Hansson in 2003. Since then many applications have been created using Ruby on Rails and presently this has been used in various applications like twitter [http://www.twitter.com] e-commerce[http://www.shopify.com/], live video streaming [http://www.hulu.com/], group chat application [http://campfirenow.com/?source=rails].


== Projects better suited for Python ==
{|border="1" cellpadding="10" cellspacing="0" align="center"
|-
!Applications better suited for Ruby
!Applications better suited for Python


|-
|The most prominent application of Ruby is in web development using Ruby on Rails.
|Python has many frameworks and the notable two among them are: Django and TurboGears.


Python has two web development frameworks: Django and TurboGears. Apart from web development, Python also provides platform for applications like Database Access, Desktop Graphical User Interface(GUI) development, Software development, Game and 3D graphics development.
|-
|Ruby on Rails is an open source web framework and Rails was created by David Heinemeier Hansson in 2003.
|Django was created by Lawrence Journal-World and was first released during July 2005. Turbogears was developed by Kevin Dangoor and Mark Ramm and its stable version was released during August of 2009 .
 
|-
|Many applications have been created using Ruby on Rails and presently this has been used in various applications like twitter [http://www.twitter.com] e-commerce[http://www.shopify.com/], live video streaming [http://www.hulu.com/], group chat application [http://campfirenow.com/?source=rails].
| Apart from web development, Python also provides platform for applications like Database Access, Desktop Graphical User Interface(GUI) development, Software development, Game and 3D graphics development.
One of the best examples of open source Python language is the "Zone Application server" [http://c2.com/cgi/wiki?ZopeApplicationServer].
One of the best examples of open source Python language is the "Zone Application server" [http://c2.com/cgi/wiki?ZopeApplicationServer].
|}
== References ==
[1] "Ruby v/s Python" http://www.c2.com/cgi/wiki?PythonVsRuby <br>
[2] "Lambda the ultimate" http://lambda-the-ultimate.org/node/1480 <br>
[3] "Ruby" http://en.wikipedia.org/wiki/Ruby_(programming_language) <br>
[4] "Python" http://en.wikipedia.org/wiki/Python_(programming_language) <br>
[5] "Ruby, Python, Power" http://blog.ianbicking.org/ruby-python-power.html <br>
[6] "Python vs Ruby " http://regebro.wordpress.com/2009/07/12/python-vs-ruby/ <br>
[7] "Python vs Ruby" http://wiki.python.org/moin/PythonVsRuby <br>
[8] "Turbogears" http://en.wikipedia.org/wiki/TurboGears <br>
[9] "Django" http://en.wikipedia.org/wiki/Django_%28web_framework%29 <br>
[10] "Python" http://www.penzilla.net/tutorials/python/control/ <br>
[11] "Book on Ruby procs,Methods,Blocks" http://www.scribd.com/doc/2027524/Ruby-Blocks-Procs-And-Methods?autodown=pdf <br>
[12] "Ruby Tutorial" http://www.fincher.org/tips/Languages/Ruby/

Latest revision as of 00:36, 17 September 2009



Ruby vs Python

Definition of Ruby and Python

Ruby is a dynamic,interpreted language that includes a powerful set of libraries. While it is often referred to as a scripting language, it is a pure objected-oriented language that has sufficient expressiveness for general-purpose applications.It combines syntax inspired by Perl with Smalltalk-like features.

Python is an object-oriented scripting language with dynamic semantics.Its design mixes software engineering features of traditional languages with the usability of scripting languages.

Differences in their language features

1.The first thing to be noted in Ruby is that,everything is an object, whereas in Python we have the liberty to code without using objects.

Ruby:String and numbers as objects

if x.between?(7,12) do ... 

2.In ruby, the programmer can use blocks to extend the language for application specific control statements where as in Python we are supposed to use only the control statements provided by the language.

Ruby Blocks:

 def aliens
if block_given?
  i = 1
  j = 2
  yield(i, j)
 else puts “magick”
 end
end
aliens { |x, y| puts x }
aliens

In this case if the block is provided to the method, it executes the if statement, otherwise it executes the else statement

Python Control statements:

# Continue
nlist = []
for i in xrange(0,100):
    if i == 0:
        continue
    nlist.append( 7 / i )
# Break
# How many heads can we flip in a row?
heads = 0
while 1:
    if x = 0:
        break
    else:
        x = random.rand(0,1)
        heads += 1
# Pass
# If you don't want to do anything in a case
x = 0
while 1:
    if x <= 100:
        pass
    elif x = 101:
        print "Just enough Dalmations!"
    else:
        print "Argh!  Too many Dalmations!"
        break
    x += 1

3.Ruby protects class attributes.We can’t access attributes of objects from outside the class. Python doesn’t protect our code from other programmers. If they want to shoot themselves in the foot they are allowed to do so.

Ruby code snippet without attributes:

 class Person
 def fname
   @fname
 end
 def fname=(fname)
   @fname = fname
 end
 def lname
   @lname
 end
 def lname=(lname)
   @lname = lname
 end
 end

Ruby code snippet with attributes:

class Person
 attr_accessor :fname, :lname
end

4.In Ruby, there are no functions, but there are methods, blocks and lambdas. All of them seem to have subtle differences, and sometimes we need to not just call them, but use .call(). In Python, there are only functions. Lambdas are functions whose name is <lambda>. Methods are functions that are wrapped, we don’t have to pass self.

Ruby Method:

class Boogy
def initialize
@dix = 15
end
def arbo
puts "#{@dix} ha\n"
end
end


b = Boogy.new # initializes an instance of Boogy
b.arbo # prints "15 ha"


Python Lambda:

def make_incrementor (n): return lambda x: x + n
f = make_incrementor(2)
g = make_incrementor(6)
print f(42), g(42)

gives output 44 48

5.The one line nameless mini-functions that can be created in Python are called Lambdas where as its Ruby counterpart is called as Blocks. Not only the name is different but also Blocks have some terrific advantage over lambdas. One of the most notable advantage is that Ruby blocks are more powerful, in that the interaction between the blocks and its contents is quite easy where as its almost impossible for the interaction between lambdas and its contents in Python. The other advantage is that Ruby blocks have access to the variables in the scope in which they were defined. This allows blocks to be used in a more expressive manner.

code snippet for computing the largest of two numbers using python lambdas

  >>>bigger = lambda a, b : a > b
  >>>print bigger(1,2)
  False
  >>>print bigger(2,1)
  True

code snippet for computing the square of each number in the array using ruby blocks

  array = [1, 2, 3, 4]
  array.iterate! do |n|
  n ** 2
  end
  puts array.inspect
  # => [1, 4, 9, 16]


6.Python has a much greater range of libraries available to it, and most of those libraries are more mature and better documented than their Ruby counterparts.

Example of a python library : "all"

  def all(iterable):
   for element in iterable:
       if not element:
           return False
   return True


7.As far as readability is concerned, Python is considered to be easily readable whereas Ruby’s code is considered to be on the downside for readability.

Differences in Programming Environment

Both Ruby and Python run on almost all the user friendly platforms like Windows9x/2000/NT, Unix, Mac-OS, MS-DOS. The difference in their programming environments is very subtle.

Python has a Virtual Machine which optimizes certain functions like hash functions and sorting algorithms.

Ruby as such does not have any virtual machine but it acts as an interpreter. There is a project going on for building a virtual machine for Ruby- the YARV [1].

What Ruby has and Python does not have?

Ruby has continuations, where as Python does not have it. One notable use of continuations in Ruby is for breakpoints in debuggers. Continuation is an abstract representation of the control state, of the things to come. Practically continuation support in a language means we can “save” our state at a point and return to it later. This is called a first-class continuation.

In ruby, the callcc method is used (it’s Kernel#callcc) to create a Continuation class. Look at this small sample:

def loop
  cont=nil
  for i in 1..4
    puts i
    callcc {|continuation| cont=continuation} if i==2
  end
  return cont
end
c = loop
c.call

In irb this will print 1,2,3,4 then 3,4 again, then exit. As a script file run by the main ruby interpreter, this will loop forerver as it captures the control state of the program when and where it was called and this includes returning the continuation and then calling it again.

What Python has and Ruby does not have?

1.It’s worth mentioning that Python has some big features like list comprehensions that Ruby doesn’t.

 [foo(x) for x in alist if bar(x) != 'frotz']

This is definitely shorter than:

  foo = [] 
  for x in alist:
  if bar(x) != 'frotz':
  foo.append(x)

2.Python uses whitespace indentation, rather than curly braces or keywords, to delimit statement blocks (a feature also known as the off-side rule). An increase in indentation comes after certain statements; a decrease in indentation signifies the end of the current block.

Indented piece of Python code:

def perm(l):
        # Compute the list of all permutations of l
    if len(l) <= 1:
                  return [l]
    r = []
    for i in range(len(l)):
             s = l[:i] + l[i+1:]
             p = perm(s)
             for x in p:
              r.append(l[i:i+1] + x)
    return r

Advantages over statically typed languages

1.Java has static typing. We declare the type of each variable, and then, during compilation, we get an error message if we use a variable of the wrong type. Ruby, on the other hand, has dynamic typing: We don't declare types for variables or functions, and no type-check occurs until runtime, when we get an error if we call a method that doesn't exist. Even then, Ruby doesn't care about an object's class, just whether it has a method of the name used in the method call. For this reason, the dynamic approach has earned the name duck typing: "If it walks like a duck and quacks like a duck, it's a duck."

Duck Typing

class ADuck
    def quack()
        puts "quack A";
    end
end
class BDuck
    def quack()
        puts "quack B";
    end
end
# quack_it doesn't care about the type of the argument duck, as long
# as it has a method called quack. Classes A and B have no
# inheritance relationship.
def quack_it(duck)
    duck.quack
end
a = ADuck.new
b = BDuck.new
quack_it(a)
quack_it(b)


2.In Ruby, variables do not need to be declared and are free to change type from statement to statement. So the following code, where the variable x changes from a FixNum (an integer that fits within a native machine word) to a String to an Array, is a perfectly legal sequence of Ruby code:


x = 10
x += 4
x = "My String"
x = [1, "My String", Hash.new ]

3.Ruby's dynamic typing means you don't repeat yourself: In Java have we had to suffer through verbose code along the lines of

 XMLPersistence xmlPersistence = (XMLPersistence)persistenceManager.getPersistence(); 

Ruby eliminates the need for the type declaration and casting (as well as parentheses and semicolon): a typical Ruby equivalent would be

 xmlPersistence = persistence_manager.persistence.

4.In Java, we often iterate over a collection's Iterator, running the logic on each element. But the iteration is just an implementation detail: in general, we are just trying to apply the same logic to each element of a collection. In Ruby, we pass a code block to a method that does just that, iterating behind the scenes. For example,

 [1, 2, 3, 4, 5].each{|n| print n*n, " "} 

prints the string 1 4 9 16 25; an iterator takes each element of the list and passes it into the code block as the variable n.

Comparison of Ruby and Python based on their Application

Applications better suited for Ruby Applications better suited for Python
The most prominent application of Ruby is in web development using Ruby on Rails. Python has many frameworks and the notable two among them are: Django and TurboGears.
Ruby on Rails is an open source web framework and Rails was created by David Heinemeier Hansson in 2003. Django was created by Lawrence Journal-World and was first released during July 2005. Turbogears was developed by Kevin Dangoor and Mark Ramm and its stable version was released during August of 2009 .
Many applications have been created using Ruby on Rails and presently this has been used in various applications like twitter [2] e-commerce[3], live video streaming [4], group chat application [5]. Apart from web development, Python also provides platform for applications like Database Access, Desktop Graphical User Interface(GUI) development, Software development, Game and 3D graphics development.

One of the best examples of open source Python language is the "Zone Application server" [6].

References

[1] "Ruby v/s Python" http://www.c2.com/cgi/wiki?PythonVsRuby
[2] "Lambda the ultimate" http://lambda-the-ultimate.org/node/1480
[3] "Ruby" http://en.wikipedia.org/wiki/Ruby_(programming_language)
[4] "Python" http://en.wikipedia.org/wiki/Python_(programming_language)
[5] "Ruby, Python, Power" http://blog.ianbicking.org/ruby-python-power.html
[6] "Python vs Ruby " http://regebro.wordpress.com/2009/07/12/python-vs-ruby/
[7] "Python vs Ruby" http://wiki.python.org/moin/PythonVsRuby
[8] "Turbogears" http://en.wikipedia.org/wiki/TurboGears
[9] "Django" http://en.wikipedia.org/wiki/Django_%28web_framework%29
[10] "Python" http://www.penzilla.net/tutorials/python/control/
[11] "Book on Ruby procs,Methods,Blocks" http://www.scribd.com/doc/2027524/Ruby-Blocks-Procs-And-Methods?autodown=pdf
[12] "Ruby Tutorial" http://www.fincher.org/tips/Languages/Ruby/