Ruby: Productive Programming Language

A brief overview of popular languages and how Ruby matches up.

Every few years something significant happens in the land of computer programming. In my opinion the Ruby computer language is such a landmark.

Over the years I have seen programmer productivity go up. These are no hard measured calculations, but I have the impression that every five years the speed of delivering software doubles. Not only that, the curve for writing maintainable software appears to increase linearly too. A lot of that speed can be attributed to the tools of a developer, and core to these tools is the computer language.

A Short Overview of Mainstream Languages

Computer languages are essentially alike. There are more similarities than differences between any language. Nevertheless, the differences have a large impact on solving problems, finding ways of expression and human interaction. For example, LISP, a language of great beauty and simplicity in conception, reflects its allegiance more to computers than to humans. A language easy to interpret is not necessarily easy to program, as many a student can attest. LISP's most amazing feature is that it shows with how few rules one can create a powerful computer language.

Structured languages like Pascal and C clearly bridged a gap between native assembler and quick, human-readable coding. C is still widely used where performance matters--it is possible to write close to the assembler, as the Linux and BSD kernels prove.

With C++ in the early nineties, I personally went through a period of exploration and discovery. Classes, objects, containers, operator overloading, the works. Reading Stroustrup's classic book was crucial to understanding C++ as a language, and I loved it. But with hindsight I can see it takes something extra to become productive in C++; it is not for everyone.

Java came to the rescue. A much simpler language with an elegance in OOP (object-oriented programming), Java does have some down sides, like slow JVMs dealing with large libraries. The language itself has some short comings too. Many experienced C++ programmers use Java, and the complaint will come that it feels like working with their hands tied behind the back. Nevertheless Java is great for corporate-type team programming efforts. As a language it goes some way in enforcing structure and using OOP concepts.

In parallel, two other languages made a mark in the nineties: Perl and Python. Both are (interpreted) scripting languages and have some real advantages over C++ and Java in terms of delivery time of software (more on that below). With current levels of computing power, performance is hardly an issue for most "user-land" software.

Perl was a revolution in a way. and most of its productivity boost was due to the introduction of a full programming language with light notation for regular expressions, arrays and especially hashes.

Perl has some real problems, though, as almost everyone will assert who has participated in large Perl programming efforts. Perl has OOP extensions, but they are non-obvious and laborious. I did enjoy learning Perl OOP because it taught me a lot about OOP itself and how to implement OOP in a language as a single hack. Writing Perl OOP, however, is no joy. Maintaining a large Perl source base is only possible with the highest level of discipline by the coders, and the language itself does not help enforcing correct coding practices.

Python is cleaner as a language though its OOP was added as an afterthought--and it shows. I spent some serious time looking into Python and did not like it that much. It gives a lot but runs short, for example, with object elements all being public. In a team effort, that means developers have trouble understanding how their classes are being used (or abused). In this situation, I would even have trouble trusting my own code. Operator overloading is ugly, the syntax of a colon after an if statement I find to be non-obvious, etc. The indentation idea is clever, but somehow it doesn't improve code readability. In short, Python almost makes it but not quite.

Introducing Ruby

Late last year I got my hands on the Ruby book by the (self-named) pragmatic programmers, Dave Thomas and Andy Hunt. The book also has an on-line version. I read the book in one go, and it goes into the hall of fame of important computer books, as far as I am concerned, right next to the Stroustrup. After reading it, I almost skipped sleep for a week because I was so excited by the implications of Ruby, a programming language that reads like poetry.

The author of Ruby, Yukihiro Matsumoto, aka Matz, knows his languages (LISP, Small Talk, Perl, Python and others) and aimed to create his perfect language. Ruby follows the Principle of Least Surprise and, funny enough, gets close. It feels, in fact, exactly like the computer language I have wanted to design all my life (without really knowing it).

Ruby was developed after 1994 and does not carry the baggage of Perl and Python; it is the new kid on the block. It comes with extensive libraries, not as rich as Perl's CPAN, but after a year of working with Ruby, I haven't missed any critical components. Ruby is complete with HTML and FTP classes, CGI support, XML parsers, database libraries, GTK and Qt bindings and even a pure Ruby BTree library. It is also quite straightforward to link up Ruby and Python libraries, which gives it an even richer base. Ruby is well supported on UNIX and Windows; developing on UNIX and deploying on Windows works without a hitch, including GUI development.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Dynamic language

Sonia's picture

A dynamic, productive, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.

ruby productivity measured

Orban Botond's picture

I made another kind of comparison.
I have implemented the "payroll" application from "Agile Software Development" in ruby. It took me 10 times less LOC than the author wrote it. Great isn' it.

Here is my post about it:
http://orbanbotond.blogspot.com/2008/01/ruby-on-rails-productivity.html

I think the names make a difference

Anonymous's picture

Ruby sounds friendlier and more valuable than Python, and less icky than a collection of oyster spit... if it was called Diamond, it would be popular with the girls (and my wife would like it 'coz diamonds are worth 3 points and rubies only 1 in Rocks'n'Diamonds).

Yeah, -99, Totally Frivolous, I know.

The ruby book I'd like to see

Anonymous's picture

I'd like to see a ruby book that covers the design aspects of OO programming, like 'the decorator pattern', 'the flyweight pattern', etc. I think ruby would be an excellent candidate for teaching this patterns to those interested in gaining OOP expertise.

Re: I'd like to see design patterns in Ruby....

Anonymous's picture

Great first language

Anonymous's picture

Ruby also makes a great first language for those just starting to learn programming. The syntax is clean and simple and Ruby's underlying architecture is very consistent. You'll also learn a lot about OOP in the process.

Re: Ruby: Productive Programming Language

Anonymous's picture

Maybe I am worse than other developers, but I find I often have to execute an edit/compile cycle because of an end-of-line typo.A text editor with syntax highlighting would probably fix that one for you.

Probably not

prog_man's picture

I think he's talking about forgetting the end of line semicolon ';' that is required in most languages (In Ruby they are optional). Syntax highlighting won't help you catch that one.

Re: Probably not

Anonymous's picture

Autoindenting (as in suitable emacs modes) catches

it very nicely -- you can see the next line doesn't indent

correctly if you're missing a ';'.

Re: Probably not

Anonymous's picture

Yeesh! We've already got a Ruby vs. Python religious war going on here. Let's not bring Emacs into it!

Emacs autoindenting probably does catch 90% of my syntax mistakes, though. And it works with Ruby. ;)

bah Emacs! VI would catch

Anonymous's picture

bah Emacs! VI would catch it twice as fast, correct it for you and give you a tip on how to write the rest of the program!

Re: Ruby: Productive Programming Language

Anonymous's picture

I'm a perl hacker turned python programmer who is occassionally tempted by new languages. Ruby has tempted me a few times for different reasons: the main one just due to the very visible large amount of activity around the language (the rapid proliferation of modules and whatnot). However I've never gotten in to Ruby, and each time i'm tempted by it the temptation is shorter lived. I always come away feeling just the opposite of this article's author: that Ruby is a sort of bastard child of python, perl and java combined, taking good elements of each, but when combined they make for a horrific mix. Perhaps this is just me. Obviously the author of this article sees things just the opposite. And different people will see things different ways. Some people even still really like perl, after all!

However, everyone should note the corrections to the author's statements about various languages, especially Python. It shows that while he has his own valid experiences, he certainly doesn't know Python as well as he lets on he does.

Bastard child of ?

dsm's picture

I read your "bastard child" comment with great amusement.

I began programming in assembler on IBM System/360s in the mid 1960s & have worked with most major languages since (even did a stint as a compiler trouble shooter for Cobol & Pl/1 on mainframes). Have done Basic-many variants, Cobol-many many variants, got into 'C' and Unix shell scripting early (1981) and worked with most shell environments from the early Unix V7 & Xenix 1.0 days up to AIX 5.3 & ksh. Did extensive work using awk & sed. Also did some Perl. In particular got into Smalltalk & Java at roughly the same time - late 1994 for Smalltalk & early 1996 for Java. I, 1997 was invited to be a presenter on the 1st Java world tour (the Asia leg).

Just recently (2004) I spent a year rewriting somone's earlier async order taking servers, written using an async package & IBM's REXX on OS/2, so we could get them onto Windows. So I have no qualms about switching languages on the basis that I will use whatever is needed to get the job done. Each language has its strengths.

One language I avoided was C++, In 1994 I made a choice to go Smalltalk after realising that to program succesfully in Smalltalk would mean I got dragged screaming & kicking into pure OOT whereas it was equally clear to me that C++ would allow anyone to write almost anything & call it whatever they liked, including in so many cases, OOT when it wasn't.

I still develop in Smalltalk and Java. As time passed I got to like Java less and Smalltalk more but the world had voted in terms of popularity & Smalltalk is on a slide out of the way.

Then I found Ruby and RubyOnRails.

Rather than feel it was the 'bastard child' of some of the other languages that I liked, I concluded (as I am sure all intelligent insightfull developers who are freed from emotional bonds to favoured habits, will) that Ruby truly is a extraordinarity elegant integration of the best of all that I liked.

Your 'bastard child' remark appears to me to say more about yourself and your perceptions that it does about Ruby.

I haven't been so excited about a new language and its supporting environment, since Java exploded on the programming scene.

Cheers

Doug Marker

Re: Ruby: Productive Programming Language

Anonymous's picture

SUMMARY:

- There is no *evidence* that Ruby's design is "friendly" whereas there is for Python.

- Evolutionary processes can and do create elegant designs.

DETAIL:

I would and do pick Python for one simple reason:

It was designed to be user friendly, easily readable, etc.

Ruby was not.

Python came from languages where readablity was actually studied. [Note: If you can read dutch or want to send away for the study you can.]

Ruby syntax is supposed to be an improvement on some other language's syntax: Well prove to me that it is an improvment! [Note: There is none. Did Matz sit 1 000 programmers down with different syntaxes to determine which was was more "intuitive"? No.]

Every statement like "@ and @@ are simple indicators that once learned help a lot" -- are meaningless. This statement is backed-up by nothing! We are supposedly Computer SCIENTISTS -- where is the science in Ruby's design?

In short, a language designer ought to also be cognitive scientists, linguists, etc. AFAIK, neither Matz or Guido are -- but at least Guido made the EFFORT to study readability! And for this effort, I use Python.

Can I learn Perl's special vars? Yes. Can I learn Ruby's member scoping rules? Yes. But just because I can memorize rules does not mean the usability is high.

As for tacking on OO -- even if so what is wrong with doing so? I believe evolution creates elegant designs; and unless Ruby is either perfect or will never change SOMETHING will be "tacked on" and will you call it bad?

Computer Scientists != User Interface Designers

Anonymous's picture

Yes, we all know how evolution leads to elegant architectures. Take Perl for instance - oh wait, nevermind ;-).

Actually, you are right - to a point. In fact, Grady Booch in "Object Oriented Analysis and Design" expressly states that a successful system cannot be gotten right the first time, but must be built incrementally and iteratively, an evolutionary process. However, he also makes it unambigously clear that there is one property that a system *must* have at the beginning for a successful evolution to occur: "The existence of a strong architectural vision". Ruby is based on a simple, strong architectural vision - the proven, Smalltalk-like pure object-oriented language. Python is based on several competing, vague visions - first a procedural scripting language, then an object-oriented language, then a functional language. Each one added piecemeal, degrading the architectural purity of the system.

Computer scientists, in general, are not overly concerned with "friendliness". BASIC, and VB, were designed to be "friendly" - but they are almost unversally denounced by programmers as awful programming languages. From a CS perspective, a language stands or falls based on the soundness, elegance, and completeness of it's basic architecture. Python's architecture is a congealed mess of ideas, whereas Ruby is based on an extremely sound, elegant, and complete Smalltalk-like architecture. However, even if you believe that "friendliness" is more important than elegance, consider the "self" declarations in Python methods. They are an eyesore, a burden to the beginning student of OOD, a gaping hole in Python's "friendliness". And their sole reason for existance? A crutch for the compiler because of the half-assed way OO is tacked-on. This is why a sound architecture is necessary for the start, even if your goal is "friendliness" rather than consistency. A vague initial vision will effect every aspect of the resulting system. Consider also the confusing mixed-messages the beginning Python student recieves when reading other's code - strings manipulated either with the string module or the built-in methods, depending on when the code was written. User classes descended either from UserList( or whatever it's called) or List depending on whether the code was written pre- or post- Python 2.2. Code that hacks around Python's former lack of real scoping, or code that doesn't - depending on the era in which it was written. The beginning student cannot get a clear picture of proper Python style because the language is such a moving target even many years after it's inception.

Strangely though, despite Guido's user-studies, I find Ruby code to be almost invariably easier to read than Python. Names are better-chosen, control structures are more readable (e.g. "9.times do ... end" instead of "for i in range(0,9): ...", and in general Ruby is terse without losing readability (and no, there is never any reason to use the perlish line-noise variables like $_ if you don't want to). Also, while this is hardly conclusive, I once sat my wife ( a non-programmer) down in front of a simple loop coded in various languages including idiomatic Ruby and Python. She immediately identified the Ruby example as being the most readable, including correctly identifying what it did. There's just something inherently more readable about the Ruby "collection.each do ... end" set of idioms than the Python "for x in y:" syntax. But of course, that's opinion.

Re: Computer Scientists != User Interface Designers

Florent's picture

You know quoting is not as convenient here as on Usenet. If you don't write reasonably short paragraphs, don't expect useful followups to you posts.

Re: Computer Scientists != User Interface Designers

Anonymous's picture

If language designers are not "user interface designers" then we should stop all the baseless, irrational discussion of which is more readable. Only until such things are taken seriously with real science behind them will the discussion be fruitful.
Until then, Python is the only scripting language I know that made any effort along these lines -- and ought to be recognized for it and not dismissed with 'well, I like ____ better' (which is not appropriate from computer "scientists" or any rational being).

In response to one particular part of your/this comment; are not the following basically the same:

self.length = length

self.width = width

self.area = length * width

and

@length = length

@width = width

@area = length * width

How is this any different? How is 'self' (or as I am sure you know, 'self' may be 'this', or 'me', or 'instance', or 'this_here_object', or '_') worse than '@'??

Re: Computer Scientists != User Interface Designers

Anonymous's picture

"In response to one particular part of your/this comment; are not the following basically the same:

self.length = length

self.width = width

self.area = length * width

and

@length = length

@width = width

@area = length * width"

Not at all, because you're leaving out part of the picture: In Python for every method on a class you've got to declare 'self' as the first argument, like:

class Rectangle:

#assuming length and width were set in the

#constructor, which I didn't define here for brevity

#and because I'm forgetting Python ;-) :

def area(self)

return self.length * self.width

#or: return self.area if it was calculated in the c'tor

What's with that 'self' you have to pass into the area method? But when you use it, you don't pass in 'self':

x = rectangle.area()

In Ruby it would be like this:

class Rectangle

def initialize(length, width) #constructor

@length = length

@width = width

@area = length * width

end

def area #actually, you could use attr_reader

return @area

end

end

#use it:

r = Rectangle.new(5,4)

x = r.area

To summarize:

* In Python 'self' is implicitly passed as the first parameter for a class' method. This is so the method gets a reference to the object it's in, otherwise it would have no idea which object it was being called on.

* In Ruby '@' indicates that the scope of a variable is within the current class (a class variable). Ruby methods 'know' whic object they were invoked on.

As far as 'readability' goes: It's subjective and in the eye of the beholder. After you learn a language it tends to be readable to you (except for perhaps Perl :)

Re: Computer Scientists != User Interface Designers

Anonymous's picture

self must be explicitely declared before it can be used. 'self.' is 4 characters longer than @. Python lacks true lexical variables. Python lacks real closures (man, don't I wish it has a real lambda?).

I think Python's greatest advantage is that while it's a 'middle-of-the-way' language, meaning of mediocre design, it is much better designed than perl and infinitely more readable than perl... And, it while it is much worse than Ruby in its design, readability and expressiveness, it enjoys (unfortunately, because Ruby is better, and fortunately because perl is worse) a rather large following and is mature enough to used in the enterprise. So, if you had to pick a scripting language out of the enterprise-ready languages, Python would take the cake. But it definitely doesn't take any cakes for its design, save using indent level for deliniating code blocks, which I think is a win, because it means that all Python code is guaranteed to be indented properly. I wish Guido would understand that such fascist enforcement of a guarantee is just as needed for variables: Python needs true lexical (or more accurately, private) variables. It's really hypocritical of Guido to say that convention offers enough protection for variables, but yet, convention doesn't offer enough protection for indent levels. That's just a bunch of...

Ruby is the future once it matures to the point of Python. What pains me the most about Ruby is nothing theoretical, but rather the pragmatic lack of decently old and stable modules. Man, Ruby takes the cake for having the most 0.0.0.0.1 version modules! That definitely sucks and limits its adoption to but a few visionary pioneers.

Re: Ruby: Productive Programming Language

Anonymous's picture

I'm a C++ hacker and general language hobbyist who learned Ruby and Python concurrently. It is quite incorrect to say that Ruby is a child of either Python or Java. When Matz set out to create Ruby, one of his stated goals was to create something different from Python, which he didn't particularly like. I'd say he succeeded, because Ruby shares almost nothing in common with Python except some similar syntax and the fact that they are both dynamically-typed, garbage-collected languages. It would be far more accurate to say that Ruby is Smalltalk with Perl syntax and an influence of Dylan, Sather, Lisp, and others. With it's metaclasses, true closures, and pervasive use of iterators and generators, coding in Ruby is very distinct experience from coding in Python. There is no Python influence except inasmuch as both Guido and Matz were influenced by some of the same predecessor languages.

As for the author's Python experience, he is quite correct in what he said. Python's OO was tacked-on, which Guido has never made any attempt to deny, although he doesn't widely publicise the fact either. Read through the Python FAQ sometime. The reason for the need for explicit declaration of the "self" argument in methods, as well as the longstanding separation of types and classes, are direct results of Python's procedural roots.

Re: Ruby: Productive Programming Language

Anonymous's picture

I wonder if you had not gone from Perl -> Python if you would still feel this way about Ruby. In my experience it's a lot easier for Perl programmers to grok Ruby than to grok Python. Perhaps once one does grok Python it's difficult to grok Ruby (well, that can't be true because I've run into several Pythonistas who like Ruby).

Anyway, I'm not sure what you mean by a 'horrific mix', can you provide examples which illustrate this? In general I find that Ruby's features 'hang together' a lot better than Perl's or Python's, but this is subjective of course.

(and to be accurate, I don't think Matz borrowed anything from Java - he did borrow from Perl, Lisp, SmallTalk and Eiffel among others, but Java didn't exist yet at least not publicly).

Re: Ruby: Productive Programming Language

Anonymous's picture

Perl does indeed support closures. I use them almost daily. I agree that a mastery of the language take a long time but that's part of it's appeal. Perl is probably the most expressive language out there. If you want to code Lisp-ish, you can, If you want to code like a C programmer, you can. If you want to hack a dirty script out or a rigorous OO system, TMTOWTDI.

OO Perl is not fun

Anonymous's picture

From one who has done it more than once: OO Perl is ugly. Though I do agree with the author of the article: Doing OO Perl taught me a lot about OO inards because you have to do a lot of things yourself. That said, I really don't want to do OO Perl anymore when Ruby is so much nicer and allows me to be so much more productive.

Ruby also supports multiple styles of programming: OO, functional, procedural.

Ruby OOP vs Python OOP

Anonymous's picture

One big difference between the two is that Ruby supports single inheritance versus Python's multiple inheritance. This design choice was for simplicity's sake since multiple parents can get confusing when inheriting methods from a net of ancestors.

In my opinion, I slightly prefer Python's OO capabilities over Ruby's. Particularly as the latest release Python (2.2) has some new features[1] which greatly enhance the usability of multiple inheritance. That said, I do agree that, in Ruby, everything feels more like an object (eg 0.upto(7) ).

[1] the two specific features I had in mind were cooperative methods using the super() function and a much better method resolution algorithm.

Guido himself doubted MI's usefulness

Anonymous's picture

Here's an interesting usenet posting by Guido van Rossum (answering Bjarne Stroustrup, no less) in which he questions the usefulness of MI and is concerned about the overhead imposed by MI:

bs@alice.att.com (Bjarne Stroustrup) writes:

>MI in C++ and elsewhere isn't perfect and it isn't a panacea, but it works

>and it makes some styles of programming noticeably more convenient and

>less obscure. Naturally, it can also be overused and misused, but basically

>it works.

Point taken. However, I still worry about MI. When MI is *not* used,

it still imposes an overhead -- there is a "delta" offset in the vtbl

that is added to "this" each time a virtual function is called, but

this delta can only ever be nonzero when MI is used. I feel that this

is in direct conflict with the C++ philosophy that language features

you don't use shouldn't cause overhead.

I am also still looking for examples of the styles of programming that

are aided by MI -- anyone got pointers?

--Guido van Rossum, CWI, Amsterdam

"You can't do that in horizontal mode."

Re: Guido himself doubted MI's usefulness

Anonymous's picture

If you read the entire thread, you'll see that Guido is wrong. MI doesn't need to cost anything if you don't use it.

Re: Ruby OOP vs Python OOP

prog_man's picture

"One big difference between the two is that Ruby supports single inheritance versus Python's multiple inheritance"

True. ( Personally, I tend to avoid using multiple inheritance even in langauges that allow it.) Ruby does have mixins, however. It means that you can define modules of methods that can be 'mixed-in' to classes in Ruby (mixing in functionality to a class). You can mix-in multiple modules to a class. While not the same as multiple inheritance, mixins can often be used as a replacement.

I've been using Ruby for well over a year now and I must say that I've never thought: "Oh, darn! I wish Ruby had multiple inheritance, I could really use it here!". Haven't missed it, but as I said above, I generally tend to avoid it anyway.

Given the choice of:

1) multiple inheritance, but no closures (Python)

2) single inheritance (with mixins) and closures (Ruby)

I'd pick #2 any day. ;-)

Wrong guesses about Python tho

Anonymous's picture

Python, like Ruby and unlike Perl, is object-oriented in the core language and all major libraries. But Python doesn't force the programmer to use OOP notation when it isn't helpful. The claim that OOP support was an afterthought in Python is incorrect.

In practice, using indentation to control block scope is a big win in code readability in spite of occasional problems with busybody text formatters and skeptical programmers. Similarly, the other statements about Python don't match my experience. Since I've looked at Ruby about as much as the author seems to have looked at Python, I'll refrain from evaluating Ruby here.

Re: Wrong guesses about Python tho

Anonymous's picture

The claim that OOP support was an afterthought in Python is incorrect.

That statement is incorrect. Read the Python FAQ. OO /was/ tacked on as an afterthought, which is the reason for a) the user having to explicitly declare the "self" argument for methods, and b) the type/class rift which is only now being remedied.

Re: Wrong guesses about Python tho

Florent's picture

"That statement is incorrect. Read the Python FAQ. OO /was/ tacked on as an afterthought, which is the reason for a) the user having to explicitly declare the "self" argument for methods, and b) the type/class rift which is only now being remedied."

Please quote the FAQ. Otherwise, this is just FUD.

At least, the answer to the question "* 6.7. Why must 'self' be declared and used explicitly in method definitions and calls?" doesn't allow saying what you assert.

Moreover, if, as you said it, "OO /was/ tacked on as an afterthought" in Python, this would not be a valid argument: does this looks familiar to you:

"Hello everybody out there using minix -

I'm doing a (free) operating system (just a hobby, won't be big and professional like gnu)"

(hint: http://groups.google.com/groups?selm=1991Aug25.205708.9541%40klaava.Hels...)

Are you suggesting Linux is not big, or not professional?

Re: Wrong guesses about Python tho

Anonymous's picture

"Python, like Ruby and unlike Perl, is object-oriented in the core language and all major libraries. "

However, Python just (as of 2.2) unified their type/object system so that you can now subclass built-in types. Also as of 2.2 Python added iterators. Since these features are so recent in Python it would tend to make sense that Python's libraries don't make much use of them yet.

On the otherhand, Ruby has had a unified type/object system and iterators from the start, so Ruby's libraries were written with these in mind. This is especially important when it comes to iterators. So while Python users will claim that Python now has iterators (and it does) it's built-in libs do not take advantage of them (at least not yet).

It must also be noted that Python doesn't have closures. While closures may seem to be an obscure feature (and they are not specifically an OO feature), once you figure out what they're good for and come to appreciate their power (it took me a while:) they can end up saving you a lot

programming time in certain applications.

"But Python doesn't force the programmer to use OOP notation when it isn't helpful."

Ruby doesn't force it either. You can define standalone methods, however, they become methods in the Object class, but you can use them in a non-OO way if you like.

"The claim that OOP support was an afterthought in Python is incorrect. "

If that is the case, then why does 'self' have to be the first parameter for all instance methods in a Python class? (and when you actually call the method you have to pretend to not use the first argument )

Python's use of indentation as a syntactical element is more of an issue of personal preference. Some people really like it and others really don't.

Re: Wrong guesses about Python tho

Florent's picture

"Python just (as of 2.2) unified their type/object system so that you can now subclass built-in types. Also as of 2.2 Python added iterators. Since these features are so recent in Python it would tend to make sense that Python's libraries don't make much use of them yet."

Well, Python's standard library is rich and runs perfectly well, so I don't see the problem.

"It must also be noted that Python doesn't have closures."

What about this:

http://www-106.ibm.com/developerworks/library/l-prog2.html

(you know about Google, don't you?)

"If that is the case, then why does 'self' have to be the first parameter for all instance methods in a Python class?"

Well, because it *is* an argument. A method is a function related to a class. When called, it has to know to which instance of the class it is to be applied.

"(and when you actually call the method you have to pretend to not use the first argument )"

This is wrong. When you write (sorry for the indentation):

class MyClass:

def foo(self, arg1):

print "Hey! I am no %s!" % arg1

instance = MyClass()

instance.foo("bar")

you give foo a real information by prefixing it by "instance.". You said it: an argument.

In fact, you really can supply "instance" as the first argument of foo in the "normal" way for functions:

MyClass.foo(instance, "bar")

This just means : get the function which is MyClass foo method and call it with instance and "bar" as arguments.

For more clarity (interactive Python prompt):

>>> MyClass.foo

MyClass.foo is an unbound method: it is a function related to a class, but is not bound to any instance of MyClass. You call it with the instance as the first argument:

>>> MyClass.foo(instance, "bar")

Hey! I am no bar!

or, similarly:

>>> f = MyClass.foo

>>> f(instance, "bar")

Hey! I am no bar!

On the other hand, instance.foo 1) is the foo method of MyClass and 2) is bound to the instance of this class referenced by the variable "instance":

>>> instance.foo

There is therefore no need to tell it to which instance it has to apply:

>>> instance.foo("bar")

Hey! I am no bar!

or, similarly:

>>> g = instance.foo

>>> g("bar")

Hey! I am no bar!

This is easy, isn't it? At least, it should be, for visionary people using Ruby. Or did you just move from Perl to Ruby because they look about the same? ;-)

Re: Ruby: Productive Programming Language

Anonymous's picture

Being something of a Python fan, I just thought I'd clear something up...

"It gives a lot but runs short, for example, with object elements all being public."

Actually, you can make members private in python... any identifiers that start with two underscores (ie, __myvar) are private.

Personally, I don't see what Ruby has to offer that Python doesn't, and I find Python syntax much more readable. But, to each his own.

Re: Ruby: Productive Programming Language

Anonymous's picture

this isnt actually true, if you use __myvar in python it becomes munged internally to __Class_myvar (or something similar, i forget), but is still accessible outside the class. this is the type of dirty hack that you dont find in ruby.

Re: Ruby: Productive Programming Language

Florent's picture

Unless you are more accurate, this is just FUD as this interactive session demonstrates (sorry for the indentation, which is not preserved AFAIK by this web site's engine):

>>> class A:

... pass

...

>>> a = A()

>>> a.__myvar = "This is FUD"

>>> __A_myvar

Traceback (most recent call last):

File "", line 1, in ?

NameError: name '__A_myvar' is not defined

>>>

Re: Ruby: Productive Programming Language

Anonymous's picture

Fundamentally, no language has any more to offer than any other. As long as the language is turing-complete, it's functionally equivalent to all others. Ruby, however, is avery, very different animal from Python. The difference is far more than syntax - the architecture is altogether different. I learned Ruby and Python together, and as a working programmer, I find Ruby to be a vastloy more productive, pragmatic, elegant, and reable language than Python. But, as you say, to each his own.

Look for Ruby to grow

prog_man's picture

I like the comment that another poster submitted:

"Ruby is Perl's younger, prettier sister."

But Ruby is growing to maturity. As a Perl refugee myself, I believe that Ruby will begin to (or I should say: continue to) attract a lot of Perl Programmers. I'm not sure about Python users, but the Perl userbase is much larger anyway. Python and Ruby tend to play in the same space: Object Oriented Scripting languages - though many would argue that Ruby (and especially the way Ruby's libraries are set up) has a much more Object Oriented 'feel'. Perl users who try Python tend to not take to it too naturally, but in my experience, Ruby is a very natural progression from Perl.

Some Perlists will complain that Ruby's RAA is not as complete as Perl's CPAN, but there is a lot of work being done to remedy that situation. And in some cases Ruby comes 'out-of-the-box' with some things that Perl doesn't have (unless you download them from CPAN), for example: In Ruby if you have two arrays and you want their difference:

array1 = ['a','b','c','d','e']

array2 = ['c',d']

array3 = array1 - array2

#array3 is: ['a','b','e']

Anyway, I predict that Ruby will eat into Perl's userbase and the erosion will be significant and noticeable by this time next year.

Re: Look for Ruby to grow

Anonymous's picture

The Pike language has had this feature for a long time.
As well as (e.g.):

array a = ({1,2,3}) | ({2,3,4});
// a is ({1,2,3,4})
array b = "Pike programming language" / " ";
// b is ({ "Pike", "programming", "language" })

and many other small conveniences.

It is also an OO interpreted language, and has excellent performance.

Re: Look for Ruby to grow

prog_man's picture

"The Pike language has had this feature for a long time. As well as (e.g.):

array a = ({1,2,3}) | ({2,3,4});

// a is ({1,2,3,4})"

Well, of course you can also do this in Ruby:

a = [1,2,3] + [2,3,4]

# a is [1,2,3,4]

"It [Pike] is also an OO interpreted language, and has excellent performance."

Looks like Pike is statically typed. Ruby is dynamically typed like Python or SmallTalk. Doing OO programming in a dynamically typed language 'feels' a lot different than doing OO in a statically typed one. I prefer the freedom of dynamically typed languages - it seems like I can get a lot more done with less code and in less time.

-prog_man

Re: Look for Ruby to grow

Anonymous's picture

> Well, of course you can also do this in Ruby:

OK, of course I'm not surprised.

In Pike, however, a+b is a different operation

from a|b (assuming a and b are arrays):

array a = ({1,2,3})

array b = ({2,3,4})

// a|b is ({1,2,3,4})

// a+b is ({1,2,3,2,3,4})

> Looks like Pike is statically typed.

Not really. Pike's type system is quite flexible, you can

usually constrain a variable's type as much (or as little)

as you like, so that run-time errors or warnings may be

generated when the actual value doesn't make sense.

E.g. the following are valid variable declarations in Pike:

int(0..10) k;

string|array(string) foo;

int|float bar;

function(int:string) fun;

mixed whatever;

with `mixed' meaning the variable is allowed to have any

type at all.

Re: Look for Ruby to grow

Anonymous's picture

>OK, of course I'm not surprised.

>In Pike, however, a+b is a different operation

>from a|b (assuming a and b are arrays):

Ok to use + ou | in Ruby. And *, & and a lot of

methods.

Full reference in

http://www.rubycentral.com/book/ref_c_array.html

Using Python libraries in Ruby?

Anonymous's picture

"It is also quite straightforward to link up Ruby and Python libraries"

How does one go about doing this? I've been following Ruby for several months now, but I've never seen this mentioned before.

???

Re: Using Python libraries in Ruby?

Anonymous's picture

A few seconds of perusing Ruby's website (the Ruby Application Archive, in particular) reveals:

-----

Ruby/Python is a Ruby extension library to embed Python interpreter in Ruby. With this library, you can use the libraries written for Python in your Ruby scripts. The most powerful feature of Ruby/Python is its transparency.

-----

I've never used it, but you can read more at:

http://www.ruby-lang.org/en/raa-list.rhtml?name=Ruby%2FPython

But it only works with Python-1.5

Anonymous's picture

Seems someone should look into updating this lib.

Re: Ruby: Productive Programming Language

Anonymous's picture

The things that have turned me off from Ruby every time I've

looked at it have been

- Lots of inline regex a la perl

- Many strange operator symbols.

Your examples don't show any of this. Is the heavy

punctuation and inline regex something that is specific

to perl converts, or is it intrinsic to the language?

- jrodman

Re: Ruby: Productive Programming Language

Anonymous's picture

The inline regex syntax is convenient to save keystrokes when coding, which is probably why it was carried over from Perl. But in Ruby it would be more "intrinsic" to do regex manipulation using the nice clean methods of the Regexp class. In my experience, the fact that Python lacked Ruby's built-in regex syntax often made it considerably less convenient for simple text processing.

Re: Ruby: Productive Programming Language

Anonymous's picture

It seems funny to me that anyone would consider "inline regex"s a turnoff. When going from Python to Ruby that was one of the things I liked! Of course, in Python you don't want inline regexes because they would be recompiled every time they are used. In Ruby (ane Perl), the compiler is aware of regex syntax so can precompile the regex. I prefer to see simple regexes inline rather than having to leave the current context to find its definition somewhere else.

As to strange operator symbols -- well, strange is a function of familiarity. I agree, Ruby could have done without inheriting those special globals from Perl ($_, $&, etc.), but Python has its own wierd stuff too -- these couple come to mind:

Looping over lines of a file:

Python:

for x in file.xreadlines(): # this is the recently improved way replacing the old, 4-lines-of-code way!

Ruby:

while line = file.readline

Loop over integers from 1 through 10:

Python:

for i in xrange(1, 11):

Ruby:

for i in 1..10

Those Python constructs might look normal to someone who is familiar with Python, but for anyone else I'll bet the Ruby way is more intuitive.

Both Python and Ruby are excellent languages. Having used both extensively, I personally somewhat prefer the way Ruby does things.

Re: Ruby: Productive Programming Language

Florent's picture

Your loop example is wrong.

In Python < 2.2, you can write:

for line in file.readlines():

(you don't *need* xreadlines)

and in Python 2.2 and above, as files support the iterator protocol, you can simply write:

for line in file:

The whole article above is real crap that shows only one fact: the author knows nothing about Python (and by the way discredits the Ruby community). Too bad.

I made a point-by-point reply to this article in French to the friend who pointed me to it. I'll translate it if someone here proves to be worth it (and asks me).

Re: Ruby: Productive Programming Language

Anonymous's picture

Florent,

Python 2.2 was released on December 21, 2001 and the author claims to have switched to Ruby in March 2001. Please do the math.

Stephan

http://branczyk.org/

Re: Ruby: Productive Programming Language

Anonymous's picture

Actually your Ruby examples are still a bit verbose :

Looping over lines of a file:

file.each { |line| ... }

Loop over integers from 1 through 10:

(1..10).each { ... }

__

Guillaume.

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix