Python Vs Ruby

So, how do PythonLanguage and RubyLanguage compare? They look more similar to each other than either does to Perl. What are the differences?

Points of comparison:

(See also PythonVsRubyCodeExamples, PythonRubyAttrComparison, PythonRubyInitializer)


Preliminary comments

Note to the reader: it is impossible to figure out what is going on here, and you will most likely not be able to get any useful information from the nonsensical ramblings and half-conversations here. Good luck.

I think that the page is a collection of comments from people who mostly have strong views on the matter.

Introduction

I just read a good interview with Matz (YukihiroMatsumoto), and found a paragraph to keep in mind when discussing PythonVsRuby and other language HolyWars:

Instead of emphasizing the what, I want to emphasize the how part: how we feel while programming. That's Ruby's main difference from other language designs. I emphasize the feeling, in particular, how I feel using Ruby. I didn't work hard to make Ruby perfect for everyone, because you feel differently from me. No language can be perfect for everyone. I tried to make Ruby perfect for me, but maybe it's not perfect for you. The perfect language for GuidoVanRossum is probably Python. -- YukihiroMatsumoto [http://www.artima.com/intv/ruby.html]


Overview

Both languages are HighLevel, GarbageCollected, and DynamicallyTyped. Both provide an interactive shell, standard libraries, and persistence support.

The reader should be warned that many comments on this page come from people who know only one of the two languages - not both.

So far Pythonistas have emphasized their language's ease through consistency, extensive libraries, docs, etc, and argued that Ruby's advantages in elegance are overstated or nonexistent. Rubyists have stressed their language's ease through conceptual elegance, slightly greater depth of OO, the power of BlocksInRuby, and the nice feeling you get from doing things the RubyWay.

A few others have objected that the whole idea of being a "fan" or "-ist" of a language is very silly.

Interestingly, those who raise this objection tend to come down on the PythonLanguage side. Perhaps this indicates a fundamental difference in the philosophy and target audience of the two languages? -- AnonymousDonor

This is a very silly assumption, which is indeed incorrect based on arbitrary perception. I like Ruby, have never in person talked to someone who codes solely in python, and personally do not code in Python because I needed an OOP approach finally - but being a fan or ist for anything is really stupid. You go for something because you like this or that way, BUT the ultimate way is how YOU think, not how any language thinks about a particular problem -- Shev

How could a such a non-partisan be on the "PythonLanguage side"?

Probably because Python came first for them and they feel that Python is practical enough to not warrant switching sides.

For an excellent discussion of the issues by AlexMartelli, one of the big lights in the PythonLanguage community, see: http://groups.google.com/groups?selm=bhqr78021hp%40enews1.newsguy.com

I don't agree that that's an "excellent" discussion by any means. Being quite deeply into Ruby myself, it's easy to see that Martelli doesn't know what he's talking about. The key point is when he's talking about method call syntax in both languages, and complains that Ruby allows "implicit" calls to methods (that is, calling a nullary method doesn't require parentheses). There is a very good reason why Ruby's syntax works the way it does: all external access to objects is done through methods. Ruby doesn't have distinct attribute reference and method call syntaxes. foo.bar always means "send the message bar to the object that's the value of foo.

I believe that you missed the point: he was arguing that having foo.bar always send message bar to object foo is in his opinion a misfeature, but that he can see that others disagree. I happen to agree: having foo.bar mean a reference to the message bar and foo.bar() mean calling bar is useful, rather than needing to use the extra syntax Ruby requires. Reasonable folks can disagree, of course.

I think you are reading way too much into what Martelli actually says in that paragraph. He calls this a "syntax" issue, and compares it to minor syntactic differences between C and Pascal or VB. It is in fact a really fundamental difference in the semantics of objects in the languages: Ruby uses UniformityOfAccess? to enforce encapsulation of object state. If you want a "public instance variable" called bar, you define a private variable @bar, a getter method bar(), and a setter bar=(). foo.bar = 5 means foo.bar=(5). If you want trivial, Ruby can define them for you. If you change your mind later and want to make bar a computed property, you just define the methods explicitly. In short, public instance variables are a misfeature.

As to first-classness of methods, you and Martelli are overestimating the syntactic overhead. Ruby does have anonymous closures in the form of code blocks, so passing around bits of code is frankly much more convenient to do in Ruby than in Python. If you spend some time writing and reading idiomatic Ruby, you'll find that there is hardly ever a need to refer to a method; almost every situation where you'd want to do that in Python, in Ruby you use a block.


Heritage and Philosophy

RubyLanguage inherits from SmalltalkLanguage and PerlLanguage. Therefore it believes in both EverythingIsAnObject and ThereIsMoreThanOneWayToDoIt. BlocksInRuby allow the user a certain amount of flexibility in adding new control structure to the language, but not as much Smalltalk, let alone LispLanguage and SchemeLanguage. Like Smalltalk, lots of methods return self. Like Perl, it provides shortcuts.

PythonLanguage inherits from the AlgolFamily, specifically the AbcLanguage (a teaching language) and ModulaThree. It provides for objects and free functions and allows users to code without using objects if you want. It provides a fair number of features from the LispFamily, especially for applying functions to lists. Modern Python does support LexicalClosures. Most recently Python has added iterators and generators (from IconLanguage), and ListComprehensions (from HaskellLanguage). Python's core philosophy is that "There should be one - and preferably only one - obvious way to do it." It's not an absolute restriction by any means. While there are always more than one way to write code, in Python it's usually (but not always) clear which one is the most idiomatic or "Pythonic."

On the statement "Ruby tends to make more sense if you're from a SmalltalkLanguage or PerlLanguage background":

On the statement "Python makes more sense if your background is in Algol68 derived languages (Java, C, etc.) and functional languages like Scheme": In ruby this is the map function:
 my_list.map{|item| item.to_s} => ['2', '4', '53']
or more simply
 [2, 4, 53].map &:to_s #=> ["2", "4", "53"]

Python also supports the map function:
 map(str, myList) -> ['2', '4', '53']

However, list comprehensions are far more powerful, allowing "if" clauses and multiple for loops:
  [(x,y) for x in xrange(3) for y in xrange(3) if x != y] -> [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]

You can do the same as above so:
  a = []
  0.upto 2 do |i|
  1. upto 2 do |j|
a << [i,j] if i != j
  end
  end

(a different approach is discussed on PythonVsRubyCodeExamples)

or with a fewer chars:

  a=[];0.upto(2){|i|0.upto(2){|j|a<<[i,j] if i!=j}}

or even more simply:
  a = []
  3.times{|x| 3.times{|y| a << [x,y] if x != y }}

In every case, a = [[0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]]

Here's Python's equivalent:

 a = []
 for x in range(3):
for y in range(3):
if x != y: 
a += [(x,y)]

List comprehensions are clearly better for this kind of thing, however. Removing useful whitespace and jamming a bunch of code points together to save space is no saving if the result is unreadable.

Be as it may, the python code above is not very communicative of it's intent, that is, it does not clearly indicate that it is generating the permutations of digits from 0 to 2, ignoring permutations where both elements are equal. Contrast with following ruby code.

a = (0..2).to_a.permutation(2).reject { |x| x[0] == x[1] }

--Saager

Python has a permutation function as well.

a = filter(lambda x:x[0]!=x[1], permutations(range(2)))

Could be even simplier. a=permutations(range(3),2)

>>> print list(a)

[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]

A notable difference is that the Ruby code needs to use ".to_a", because .permutation is a method on array objects, and range objects don't have an equivalent method. In contrast, the Python functions work on any iterable -- including user-defined ones.

Ruby philosopy is also the OO idea of telling the object to do something, instead of doing something with the object. So you don't do string(10) but 10.to_s. -- Brian

I'm not quite sure what this is meant to prove... Python's "str" is a class, so str(9) instantiates an object of class str, which determines what to do with the integer parameter "9". Even if str were a function, would it matter? [Yes, I realise that in ruby to_s is a method of object, but...] There are advantages to using foo(blah) over blah.to_foo(), namely that if blah is missing to_foo(), you have to go and add one in, whereas foo(blah) can easily provide default behaviour without having to modify your parent class. Python objects have hooks (for example, 1.4.__str__()) for object conversion/behaviour, and heavily discourage on-the-fly modification without subclassing. It's one of those schisms that keeps Python Python and Ruby Ruby, despite any talk that PythonAndRubyAreConverging ;-).

As the previous paragraph says, str(object) calls the __str__() method of object. "str" is really a class, and "object" is the argument of its constructor. I realized how handy subclassing str (or the other builtins) is for tweaking how an object acts. For example, I recently needed to change the behavior of the dict (Python's hash type) to return False when a given key wasn't present in the dictionary. I just subclassed it and changed the behavior of its __getitem__(self, key) method. The resulting class acted exactly like a dictionary, except for the one difference I wanted. According to this article, Ruby also allows subclassing of builtins. Does it allow changing of the behavior of the objects, as opposed to just overriding regular methods?

To the previous paragraph: since objects are only interacted with via methods, overriding any methods WILL change the behavior of those objects. Also, in Ruby, you can change the behavior of an object without having to subclass it. For example, if you wanted to modify the behavior of all hashes in your code, without going through and changing every hash instantiation using hash literals to use a subclass instead, you could instead modify the Hash class itself.

  class Hash
alias get []
def [] param
get param or false
end
  end

On the other hand, note that: Python distinguishes between statements and expressions, and it does not automatically return the last expressions evaluated in a method/function, which makes it slightly more awkward for FunctionalProgramming. A None (null) return value is generally intended to indicate that the function/method has a side effect; avoiding implicitly returned values makes it explicit what the programmer intended to return from the function. (Which is perfectly in line with Zen of Python's, "Explicit is better than Implicit")

Python provides for objects and free functions and allows users to code without using objects. Not really. The truth is far more interesting: in Python everything is an object, but a good deal of cleverness has gone into making it so that you don't need to care that this is true, depending on what you're doing.

Maybe, but I don't see what this buys you. The Python language reference (http://www.python.org/doc/current/ref/ref.html) devotes a whole sub-chapter to "Emulating container types", "Emulating callable Objects", "Emulating numeric types", "Emulating sequences" etc. -- only because arrays, sequences etc. are "special" in Python. In Ruby, you just derive from the respective base classes (or extend them directly). So, Ruby's type system is much simpler and cleaner and allows a smaller and simpler language core. And, you write scripts that don't look like OOP in Ruby just as easily because the default "global" namespace is the body of a default "main" object, which just implements all the usual imperative functions like print, gets, eval, etc. -- OlafKlischat

In Python you can actually derive base types; "emulation" is for implementing standard protocols (or behavior, or interfaces) from scratch in your own classes. Say, to use a database file like a regular hash.

"Ruby can do this too. You would just implement the [] method."

Indeed, nothing stops you from inheriting from a native class/type in Python (or from all of them at the same time if that gets you high, since Python supports multiple inheritance). If you try to subclass more than one primitive type more interesting than object, you'll usually be told that "multiple bases have instance lay-out conflict".

Ruby also allows you to write scripts that don't really look like you're using objects.

Ruby people complain about Python's lack of blocks, the difficulty of doing dynamic code generation, the awkwardness of trying to modify existing classes. They complain about these things despite the fact that Python people have demonstrated almost-good-enough "Pythonic" ways of doing them. (See BlocksInPython)

These are issues with the core language (SyntaxMatters); they're much harder to fix than a missing library or tool or document. (It could be done in about four PEPs, but they'd get shouted down.) Does that make them "killer features"? -- AdamSpitz

The second two might, because what's beginning to look like the killer app, RubyOnRails, relies upon them.

Python has all the features necessary to do the kinds of things RubyOnRails does, for instance Metaclasses for domain-specific object declarations. -- IanBicking


Popularity

Well, there's really only one way to gauge this:


Readability

Most people agree that both languages rate highly. Python is farther on along providing documentation support like __doc__, but Ruby is following with the rd tool and RdocFormat. (SelfDocumentingCode)

As in all cases, much of readability comes down to what you're used to.

See PythonVsRubyCodeExamples to judge for yourself.

I use Ruby over Python when I can. But I do think Python has an advantage in the SyntacticallySignificantWhitespace. For me it can become hard to keep track of end's in nested structures. Glyphs are also relevant. Pythonists seem to loathe the @'s in Ruby, but then again I __can't stand__ Python's underscores. For me, they're the absolute worst thing about the language. (See TheProblemWithSigils)

If anyone is having problems keeping track of "nested end's" then they are not using a smart (bloated?) enough editor. In Emacs, all you do is use Ruby mode and let the auto-indent magic work. When viewing less complex Python and Ruby samples side by side, it is interesting to note how they are usually both formatted nearly identically. Just take out the "end" constructs, adjust the indent level, and a Ruby snippet might even fool an unobservant Python programmer when quickly scrolling through a webpage. The biggest thing I enjoy about the Ruby syntax over the Python syntax is being able to refactor code and have Emacs figure out how to properly indent it for me--I'm pretty lazy.

Surprisingly, while some Ruby proponents claim it doesn't enforce indentation the way Python does, the parser is sensitive to whitespace. From the Ruby FAQ (http://www.rubycentral.com/faq/rubyfaq-6.html#ss6.5):

Ruby works hard to distinguish method calls from operators, and variable names from method names. Unfortunately, there's no way it can get it right all the time. In this case, "a +b" is parsed as "a(+b)". Remove the space to the left of "+" or add a space to the right of "+," and it will be parsed as an addition. This has nothing to do with indentation. And for what it's worth, Ruby now parses "a +b" the way you'd expect. Which way is that?

When I heard about Python's use of whitespace for structure, I too was horrified, and I wrote the language off altogether. Some time later, I decided to give Python a go (mostly so I could score more points on geek tests, I think), and found that, indeed, I absolutely hated the dependence on whitespace; all the same, "I can handle C++", I said to myself, "so I can bloody well stick this out too". Half an hour later, I was hacking like mad, I'd completely forgotten about the whitespace, and I was in love with Python; I shouldn't have been surprised, but I internalized the new syntax, and after that, I didn't think about it, any more than I think about the braces in Java or the commas in English. A happy ending. The only thing is, now I'm really starting to question the usefulness of static typing, but that's another story ... -- TomAnderson

I didn't actually notice that whitespace was signifigant for structure in Python for quite a while. Considering that I would normally indent something in C++ regardless, the indenting seemed quite natural. The only surprise is when you try not to do it, and that is often because you're making something quick. The fact that Python won't let you do that will make that "quick code" look better in the long run. You really don't notice it after 10 minutes of code, and indenting everything will become quite natural (if you are lazy and don't already), especially when you start coding in another language again. -- BradleyArsenault?

Note that IDLE - the IDE that comes with python (and is built with Python) allows you to highlight blocks of text and indent, or un-indent the selected text as a whole - making refactoring easy compared to using an text editor without equivalent support. That one factor alone made any hesitation regarding indention moot. There is also a python lisp module for emacs, that can do the same thing. -- MalcolmCampbell

While Python's use of whitespace is easy for a human to handle, it can get very tricky indeed if you are generating Python for some reason.

(See the PythonWhiteSpaceDiscussion.)

I think there is difference in readability philosophy between Ruby and Python. Python tends to restrict the amount of SyntacticSugar. Ruby tends to bend over backwards to make its sweet stuff as elegant as possible, in the hope that given good choices you'll make them.

Example: In Ruby, for loops are ugly and bug-prone. BlocksInRuby, through keywords like .times, .each, and .each_index are simpler to use. Thus, in practice, for loops are uncommon. In my opinion, all except possibly .each_index are more readable. -- AnonymousDonor

On a related note to SyntacticSugar, there sometimes comes a point where doing things the canonical way becomes just plain verbose, tedious, and ugly. An example pertinent to me is Python's treatment of regular expressions. I migrated to Python from Perl due to the data structures. But the fact that regular expressions are not part of the Python language proper (save as a module), and don't have some of the sugary operator syntax of Perl, has really been a thorn in my side for what I do. Perl's treatment may seem more cryptic, but its compactness makes it much more readable in the context of scripts than Python's verboseness. I am new to Ruby but I immediately see its adoption of Perl-style regular expressions in addition to the data structures I appreciate from Python as ultimately enticing. I in fact first considered Ruby as a combination of the best of Python and Perl (though I've since learned there's more to it). Removal of the strict indentation dependence is a bonus for me as well. (I don't like to be chained to an editor, especially for quick on-the-fly edits, and I don't like that I can't if(0) out large blocks of code without marking large blocks and indenting.) -- milesh

That's why I still use Perl for small text processing jobs. Python, however, is marvelous for larger programs, where I find that regular expressions aren't nearly as important as I would have thought. On occasion the extra effort required to use them at all has made me notice that simple string replacement would be both simpler and faster. -- Eric


Ease for Beginners

Python's "vanilla" syntax makes it an acceptable choice for use as an embedding and extension language for use by non-programmers. (Ruby's ability to let users redefine fundamental behaviour, like string equality tests, would seem to disqualify it here.)

Except that Guido's CPython is currently unusable as an embedding platform due to the total lack of any sandbox/restricted execution scheme. Zope has one, but it's deep within Zope, and has gone several name changes through several thoroughly unsearchable names ("Restricted Python", "Python Methods", Script(Python)) - so it's very hard to find as a separate platform. Ruby's "safe" module isn't perfect, but it's there. -- MartinZarate

Restricted execution is missing, but it certainly doesn't keep Python from being embedded in many environments, and in fact it's quite popular for this. Jython is also a popular extension language for Java projects, and inherits Java's restricted execution. -- IanBicking

Python used to have two "restricted execution" modules: rexec and Bastion. However, changes to the language have made it much more difficult to secure, and both modules were officially declared dead in Python 2.3.

One important fact that I haven't seen mentioned is that Python has a mission to be simple for beginners. Ruby strikes me as too complex for being a good beginning language, but great for a programmer who already knows a language or two. Part of the magic of Python is that is has great appeal to beginners, professionals, and academics.

Odd. I found Ruby snake-simple to pick up. You need not think about objects, how to "include" files, or anything too "meta". Personal taste, I suppose, but found it easier to get into than Python. -- JamesBritt

Yes. I like Ruby better than Python (though lately I've become dissatisfied with both of them), but occasionally beginners have asked me for a recommendation for a first programming language, and I always tell them, "Smalltalk or Python." -- AdamSpitz

Odd. I think the best way to break in a new programmer/coder is to let him grind his teeth on C++ for a while. Provided he doesn't become obsessed with it, it is IMO the best introduction to programming. There are so many details that the programmer has to take care of himself, the language constructs are so rich that they force many low-level decisions, interaction between code and compiler is intense, and there's the macro engine on top of it, which is quite useful at obfuscating code. Whereas high level, garbage collected languages leave it all to the programmer. Thus not forcing too much "training" to happen for the programmer. Only after some C++ hell is a programmer able to properly use a high level, garbage collected, puerly OO language properly. Just my off topic opinion. -- flj

I really disagree. I'm quite a newbie in coding. In fact the first language I learned was Python, then I learned Objective-C and C, then Ruby. And I really regret that I didn't pick Ruby first instead. I'm not a specialist enough to clearly explain why, all I can say is that Ruby feels much more "logical" to me. To me, Python was easy to learn but not to use. -- Fred

One advantage Ruby has is that you don't need to 'import' external things to do simple tasks. Say getting commandline arguments. In Ruby they're just there, as ARGV. In Python, you have to import sys, then use sys.argv. It's not super difficult, but it's not as obvious either. Same goes with most of what's in the "os" package in Python. In Ruby, most of those functions are available everywhere as part of Kernel. As for Ruby's ability to redefine fundamental behaviour, *shrug*, in practice, that doesn't often happen, especially not in a destructive or dangerous way. I wouldn't consider it a serious concern. -- Merc

Namespaces are one honking great idea -- let's do more of those! -- Zen of Python. I think it's similar to the whole emacs/vi difference - if you prefer to think of editing as something you do while writing text, EmacsEditor is probably your preference. If you prefer to think of editing text and writing text as two separate but related tasks, ViEditor is probably for you. If you think you should have a SwissArmyChainsaw, then you should be using Perl (or Ruby). If you want a toolkit that contains tools for each job, you'll probably find `imports` perfectly elegant. They state, at the very beginning of the file, that you intend to do certain things. I like that - WayneWerner

I don't mean to be snide, but how is ARGV more obvious? Neither seems particularly obvious to me--in either case discovery involves reading or experience. -- LeviCook?

Correct, although because each side of the inequality contains the same factor, they cancel out. I have a feeling you know this, but 'argv' is a holdover from the C programming language, and stands for 'argument vector'. You are correct, though, that knowing this without discovery implies past experience with some programming language. -- TimLesher

Why would the ability to redefine string comparision disqualify? Do you think a beginner would get a flash and include into the all shining new high-security banking application she's writing:

 Class String
def == other
 self < other
end
 end

I'd imagine she'd just use the standard string comparision. (And maybe one would even begin with something other than nuclear warhead control programs. ;) -- Brian


Ruby Blocks and Python Lambdas

"There are many Ruby users who voluntarily converted from Python and would tend to disagree with the assertion that there are no killer feature differences. The Ruby closure syntax alone is one, for example."

(See BlocksInRuby but also BlocksInPython and BlocksInManyLanguages)

"...once you are experienced in Ruby you will find blocks to be essential."

This goes to the heart of the the major difference between Ruby and Python. In Python, you're stuck with the control statements provided by the language and have to write classes that work with those statements (by implementing methods with lots of underscores in them). In contrast, a Ruby programmer uses blocks to extend the language with application-specific control statements. Therefore programming becomes a matter of building application-specific languages in terms of primitives provided by the base language.

I agree only partly. Python's attitude is towards using uniform language constructions, but you can quite easily add new ones, because the difference between a block and a lambda is quite small. (You can have more than one lambda, while blocks, on the other hand, have closures. Nested scopes were implemented in Python 2.x)

Personally, I think this is what programming is all about, but we have become stuck with languages that are far too inflexible and syntax-heavy to allow us to program in this way. Even Ruby isn't as good for this style of programming as LispLanguage, SchemeLanguage or SmalltalkLanguage. Still, it's good to see the gradual take up of more expressive languages; eventually, we might work our way back to where we were in the 1950s! HaHaOnlySerious.

ApplesToOranges?. We're talking human-readable languages here - Python is considered executable pseudocode to many. Meanwhile, Lisp languages are really just text representations of a parse tree - easier for the computer to read than for me. I think it is impossible to overstate the advantage blocks provide to Ruby. Yes, Python has closures and lambdas - hell, C++ does too if you push a code generator hard enough. The point is that Ruby has them in a pleasant, legible manner. To see why this is important, look at the horrible mess that the Decorators debate was in the Python world. Also look at how much of a pain it is to work with metaclasses in Python. These debates would never have been started in Ruby - the syntax is already there for such things; only the conventions would remain. If Python had the block feature of Ruby (which is functionally just a really smooth syntax of lambdas) then I'd never touch Ruby again. I hope Guido learns this lesson before Python 3.0. Bragging about feature X over feature Y makes about as bunch as much sense as Gentoo users talking about "use" flags - it doesn't matter how much you can tweak your system and personalize it if nobody else wants to touch the whole platform with a ten-foot pole. Ruby's blocks are a pragmatic, intelligent concept that I'm continually annoyed is so rare in legible languages. Too bad the rest of the language is so frustrating. Still, it's better than trying to explain to a newbie what car and cdr mean any day.

The difference between Python lambdas and Ruby blocks is that Ruby blocks have access to the variables in the scope in which they were defined. (LexicalClosures. These were added in Python 2.2.) This allows blocks to be used in a more expressive manner, such as those described above.

For example, your class uses the "for .. in" statement to iterate over the private list of elements. If you want to be able to use instances of MyList in "for...in" statements, you have to add special support to your class to work with the built-in interpreter; namely, the __iter__ method. In Ruby, iteration over collections is just a method that passes each element to a block. Implementing the "each" method for a new collection (and importing the Enumerable module to mix in useful higher-order functions such as collect) makes it indistinguishable from all other collections. So both languages require you to write an iterator function rather than using magic.


Ruby Equivalents for Python List Comprehensions

Moved to PythonVsRubyCodeExamples.


Development Environments

Both languages provide interactive shells (type "python" or "irb") and high-level persistence support.

Multiple IDEs are available for Python, including GUI debuggers.

A gdb-style debugger is available for each language.

Python has a RefactoringBrowser, BicycleRepairMan. RubyLanguage now has a RefactoringBrowser too, RubyRefactoringBrowser at http://www.kmc.gr.jp/proj/rrb/index-en.html

Both languages are supported by Emacs modes. Python can be used as an elisp replacement - see Pymacs.

The current Ruby implementation is closely tied to Unix, making Windows performance and ports to new platforms problematic.

There is an EclipseIde for Ruby. RubyCocoa adds support for Ruby to ProjectBuilder/ExCode on MacOsx.


Community and Documentation

There's just not as big a community surrounding Ruby. Fewer books, wizards, tools, and libraries makes it less appealing than Python for real work.

On the other hand, the Ruby community is the friendliest and most helpful you will ever meet. I think that Ruby's community is one of the big selling points of the language. (However, the same has also been said of the Python community.)

Funny. The few people I have met from the Ruby community and especially the RoR community have all been rather arrogant and exhibited strong language bias, elitist attitude und unreasonable fanboyism. Now that is completely subjective, but there must be a reason for charts like this http://forums.macrumors.com/showthread.php?t=401640. The Python guys have all been nice so far.


Libraries

I think that this discussion so far misses many practicalities. For instance, what about UniCode. More and more software depends on Unicode. Python has rich Unicode support built-in (for example, Unicode literals, Unicode regular expressions, Unicode readers and writers). Ruby 2.0 is supposed to have something even more general than Unicode, but in the meantime it doesn't have anything built in.

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.

Ruby, however, can take advantage of Python libraries through the use of Ruby/Python (http://www.goto.info.waseda.ac.jp/%7Efukusima/ruby/python/doc/index.html) - there are, however, probably performance concerns in doing so.

Also, there is a perception out there that the Ruby standard library is smaller but better organized than the Python one.

Also, if the size of the libraries/communities/bookshelves was that important to use a language, then nobody would discuss why programming languages beyond PerlLanguage, JavaLanguage or, indeed, FortranLanguage were ever needed or wished. Nothing compares to CPAN (in my opinion). But there's obviously more to this than these things: it's not about how many books, but if there are enough good books; not how many people, but if there are enough friendly people, and so on... I'd say both Python and Ruby match these requirements fairly well, as Perl and many other languages do.

In general Python's libraries are more plentiful and more mature, so it wins, in my opinion, for COM/CORBA, XML, and networking. They're both kind of awkward for making binaries, but, um, why do you want to make binaries? Both are extremely portable. Ruby's API for C integration is much, much cleaner than Python's. Python C modules have a lot of boilerplate.

In either Ruby or Python, a poorly written extension module can block all threads. But in Ruby, it may not be possible to make a C library that does blocking calls give up its time slice at all.

Although I haven't done much with Python C extension modules, I think the main cause of the extra boilerplate is Python's use of reference counts* (with cycle detection) for garbage collection. Apparently, if you have a situation where the code you're interfacing to Ruby does anything tricky with the pointers to the wrapped objects (like storing them away for later), Ruby's mark-and-sweep GC needs to be told about them - which can cause problems sometimes. I think this is a tie again - Ruby's C interface is simpler, whereas the Python interface is potentially more flexible.

(*) specifically CPython, rather than the Java implementation, Jython

One way of wrapping C or C++ is to use the SimplifiedWrapperAndInterfaceGenerator. This can generate interface code for many languages, including both Python and Ruby.

Python has ctypes which lets you bind to DLLs at runtime (http://starship.python.net/crew/theller/ctypes/), which means you can write extensions in python.

There is pysoftwire which allows you to write python functions in x86 asm at runtime.

You can write C like extensions with Pyrex, a hybrid Python/C-like language.

There is sip for writing C++ extensions with python.

There is the BoostPythonLibrary for writing C++ extensions for Python.

According to http://modulecounts.com there are more gems in RubyGems than modules in PyPI.


Platforms

Python and Ruby are both available for UNIX, DOS, Windows 95/98/NT/2000, Mac OS X, BeOS, Amiga, Acorn Risc OS, and OS/2.

Python is also available under Apple, AS400, QNX, VMS, OS390, AROS, Windows CE. (Anybody know if Ruby supports any of those platforms?)

Python has a single, nice Windows distribution, but it has a slightly different subset of functionality than the Unix version. Some of the POSIXy functions of the os module, in particular, are not supported in Windows.

And the Apple and Windows Pythons offer unique functionality for their platforms too - COM, for example. There's no working around the fact that most of POSIX is Unix-specific. But all the stuff you need to run on all platforms - regexps and threads and sockets - does.

The Windows Ruby installation includes the Win32Api library which allows access to windows DLL calls. Code to call from and to COM is also available. RubyCocoa offers very good support for MacOs.


Applications

Any good, and big, Ruby projects out there?

The Ruby equivalent to Zope is Rails. RubyOnRails is an open source web-application framework for Ruby. Marketing fluff: Everything needed to build real-world applications in fewer lines of code than other frameworks spend setting up their XML configuration files.

Python caught up recently and has couple of web-application frameworks, each fitting different constituents (compared to "one sice fits all" Ruby approach):

Also, here is a list of Real World examples of Ruby and here is a list of major applications in Ruby.

Zope has ubiquitous undo support, provides a unified user interface and API to multiple data sources including its own database (storable inside a RDBMS by using a DA), and the filesystem. It can be managed through DAV. RubyOnRails is still evolving, although it's close to version 1.0 as of Feb 2005. It's lower-level than Zope and uses generators to flesh in some support, like authentication. Version 0.10 no longer requires mod_rewrite and permits easy use of RubyOnRails with alternate servers like lighttpd. Unlike Zope which some have called un-Pythonic, RubyOnRails is more like a souped-up Ruby that helps you build web applications. As such, it doesn't come with undos and a full-blown security model.

But on the other hand, RubyOnRails encourages you to DoTheSimplestThingThatCouldPossiblyWork, which is pleasant. It also lets you get a full-featured project up and running in much less code than Zope. It does discourage some things, and it does lack some features (lack of undo is a legitimate complaint). But you named some features that Rails has no business providing or is just plain wrong:


Performance

Sorry - I thought the fame/notoriety of the ComputerLanguageBenchmarksGame was such that everyone would automatically go to:

http://benchmarksgame.alioth.debian.org/u32/which-programs-are-fastest.php

http://benchmarksgame.alioth.debian.org/u32/ruby.php

The benchmarks game has had 3 times more Python programs contributed than Ruby programs - did the Ruby programmers lose hope?

http://benchmarksgame.alioth.debian.org/play.php#contribute

PythonLanguage has a JIT compiler called PsycoPython. It can also be compiled to JavaByteCode or DotNet ByteCode (JavaPython and IronPython). YukihiroMatsumoto is working on a VirtualMachine for RubyLanguage called Rite. Both languages are targets for PerlSix's ParrotVirtualMachine?.

PyPy is a working implementation of Python written in Python, with some advanced language translation (currently to C; other targets are expected) to make this feasible.

Ruby has Rubinius, a Ruby implementation written mostly in Ruby. See http://rubini.us/

Threads are actually pretty simple in Ruby, too. See http://www.rubycentral.com/downloads/book.html

I'd agree that threads are simple in Ruby. But the performance seems lower than the standard Python built-in threads, and much, much lower than either Python generator threads or the threads that Stackless Python provides. (Again, Ruby2 is supposed to fix this.)


Misc.

There's a (selective) list of references for comparisons of Ruby and Python at http://www.ruby-doc.org/RubyEyeForThePythonGuy.html

There's also a pair of rants at: http://www.ericw.org/rants/showrant.psp?rant=ruby http://www.ericw.org/rants/showrant.psp?rant=python


As someone who has used both (but admittedly favors python) this whole page strikes me as starkly pro-Ruby. If I had to retitle it I would call it "whyCantPythonBeExactlyLikeRuby" -- Jackdied

Indeed! Is it just because almost no Python users know of this page (and thus the ratio of Python to Ruby contributors to this page is very low)?

I didn't find this page biased towards either language -- I know Python and was looking for a comparison to Ruby. I am staying with Python so far, even though Ruby is a nice one. -- ShurikO

Well, the page clearly states that there are many more Ruby programmers than Python, so it's obvious. I, for one, stand for Python.

I think there are probably more Python programmers than Ruby. Before RubyOnRails, Ruby wasn't getting nearly as much attention. I'm not being entirely facetious when I suggest that it's because Ruby inspires a high level of zealotry, akin to Macs and Amigas. (Those of us who are Mac users also get agitated to use a commercial text editor written by a Rails developer, because, like Ruby and Rails, the incredible superiority should be intuitively obvious to even a casual observer! But that's a different grump. :) )

There are definitely more Python programmers than Ruby - probably a factor of ten, perhaps more - and certainly more Python jobs. Rails may change that.

I would guess that most Ruby zealots were/are SmalltalkLanguage zealots -- Norfy

The whole notion that Ruby could be considered in any way comparable to Python is ridiculous. It is like comparing a Yugo to a Mercedes---they look about the same when you first try them out if you've never seen a car before. After a little while, the Yugo is going to break down, but the Mercedes is going to keep going. So even the idea that you can make a serious comparison is heavily biased towards Ruby.

Please read ParkingTicket


Does RubyLanguage allow a block to return to the context that created (as opposed to invoked) it, as in Smalltalk?

Yes, though not in the same way that Smalltalk does it (with the ^ operator). Ruby has a CallWithCurrentContinuation method. So, one can create a continuation, capture it in a block, and have the block invoke the continuation. Or something along those lines.

Does RubyLanguage allow an exception handler to return a value from the expression that raised the exception and continue execution at the point where the exception was raised?

Nope. Not out of the box. Ruby's exceptions are a lot like Java's or Python's and aren't as rich as Smalltalk's at this point. Ruby does, however, give you room to implement Smalltalk-style exceptions. I don't know of an implementation of recoverable exceptions, but it looks feasible, thanks to call/cc and the fact that all of the built-ins can be overidden and redefined.

In my opinion, these are the two foundation stones upon which most other things can be constructed -- in Perl, Python and apparently also Ruby. Having built Smalltalk-style metastructure in ObjectiveCee, JavaLanguage, JavaScript, PerlLanguage, PythonLanguage, and others, the presence of metastructure is at best a convenience and at worst (as in JavaLanguage) an obstacle when done badly. LexicalClosures without the mentioned return semantics are better than no closures, but make it significantly more tedious to write reusable control structures. Exceptions that cannot be restarted or resumed are, in my opinion, essentially useless.

-- TomStambaugh

call/cc is a more fundamental continuation mechanism than non-local exit and recoverable exceptions, and I think you'll find that it makes a serviceable "foundation stone".

You certainly have my attention -- now I'll have to go try out CallWithCurrentContinuation. I'm not sure I'd call Smalltalk's behavior a "non-local exit", but I agree that if "call/cc" does the equivalent then the rest falls out by turning the crank. This is good information; now I'll have to go try it. -- TomStambaugh


I am newbie for both Python and Ruby. I started from Python and like its style very much, especially its indentation. But the name of "Python" and snake pictures/icons (e.g., on official Python Tutorial page) made me feel sick. From this perspective, ruby has a better name than python. So I searched and found ruby and so far am very happy with it. Plus it has some features like open classes, which people can modify the class anytime.

Names are important and said to carry universal energy messages in ancient cultures. That's why parents usually give their children positive names. Suggest Python changes its name to something else, like Pyson, pysong, or pysung, etc. Names like Java (good smell), Fortran (good fortune), Perl (good looking) are some other good examples. -- fr

^^^Based on this, I feel that BASIC or Alice are the best things for you to be learning...

Is this a joke? [Don't think so, sounds pretty serious to me.]

Well, PythonLanguage was named after MontyPython, a silly comedy troupe which has much more to do with parrots, rabbits, and halibuts than snakes. [Don't forget all of Monty's famous kitty/pussy puns!]

LOL - I was surprised to see someone venting the very uncomfortable feeling I felt ashamed for having. When someone, like me, doesn't have any knowledge of the actual thing, then a name does affect you because it's ALL YOU'VE GOT. Ridiculous, but true. Not only is it a snake, but I'm Swedish and in Swedish it also means something like "disgusting". It really does not invite me. Just sounds really, really bad. Ruby though... aaaah, images of beautiful women. Not sure about the rails though...

I too shared a distaste for Python's name and feeling. Snakes, eggs, old British comedy. I'll pass thank you. - EW

Ruby just brings to mind cutesy cartoons like the Twitter FailWhale

If you choose a programming language to learn solely based on the name, then you don't have anything useful to do with it as you are not choosing it based on your needs, and it is probably a waste of your time to attempt to learn either language.


See RubyLanguage, PythonLanguage, PythonAndRubyAreConverging See Also: CategoryInManyProgrammingLanguages, LanguagePissingMatch, PythonVsPerl


CategoryProgrammingLanguageComparisons CategoryPython CategoryRuby


EditText of this page (last edited February 17, 2014) or FindPage with title or text search