topaz: February 20, 2008 (lunar eclipse)
Tim Pierce ([personal profile] topaz) wrote2008-03-10 01:06 am
Entry tags:

Why Ruby is not my favorite programming language

[livejournal.com profile] khedron asked me after my last Ruby post what I thought of the language, and whether I agreed with the sentiment that Ruby can be a pretty decent substitute for Lisp in a lot of cases.

Ruby is a nifty little language that's had a small but devoted following for about 15 years.  It's gotten a lot of attention recently with Ruby on Rails, a Web development framework that implements the model-view-controller design pattern for Ruby applications.  Some things it does very nicely: its syntax is more highly reflective than any other language I can think of offhand since Smalltalk.  At some point I should write something about the cooler parts of Ruby, but right now it's annoying me and so I'm afraid that today you get the bile.

There is always the risk, when writing an article like this one, of criticizing something simply because it is different from something that you happen to like more.  I am sure this is no exception.  I will try not to criticize Ruby for not being Lisp, or C, or heaven help me, Perl, but on the basis of its own merits.

First-class functions

Many methods in Ruby are accompanied by code "blocks" where other languages might use a closure or a reference to a subroutine, e.g.:

values.sort_by { |x| x.abs }
palindromes = words.find_all { |w| w == w.reverse }

The confusing and maddening thing here is that you can't pass a function or a reference to one.  Why not?  Well, because it's not a block, and these methods will only accept a block.  What's a block?  A block is a chunk of executable code.  You mean... like a function?  Right.  I mean, actually no, not really.  What?

Trying to resolve this issue can reduce even the bravest warrior-hackers to a gibbering, cowering mess.  [livejournal.com profile] zsquirrelboy found me a very good analysis of Ruby's handling of first-class function objects by Eli Bendersky, who does an excellent job of describing the differences between Ruby's methods, Procs and blocks.  Anyone else who has struggled with this issue should go read his commentary right away.

Matz confirmed in a Ruby article in InformIT that this "block" construction is a syntactical oddity. It comes into play only when the interpreter sees an open brace (or the do keyword) supplied on the same line as an iterator method. Although it looks as though you are creating an anonymous procedure object and passing it as an argument to the iterator, the block isn't really any kind of first-class object and is not delivered to the iterator via standard argument-passing mechanisms.  According to Bendersky, the interpreter quietly transforms the block into a closure and attaches it to a special slot on the iterator method, which the iterator can invoke with the yield statement.

This technique of invoking iterator methods with blocks is convenient but I find it unsatisfying and unsettling when examined more deeply.  One of the commenters on Bendersky's essay asked, quite reasonably, why it's necessary to do this:

func = lambda { |x| x + 5 }
func.call(2)

rather than the conceptually simpler

func = lambda { |x| x + 5 }
func(2)

The answer is apparently that, because Ruby puts methods and local variables in separate namespaces, and permits methods to be called without parentheses, an expression like "func 2" would have an ambiguous parse tree.  So you're not allowed to do it.

Alan Perlis once famously said that "syntactic sugar causes cancer of the semicolon."  At long, long last, I think I finally understand what he meant.

Inconsistent variable scoping

Ruby variables are declared only in the arguments to Procs or methods. When a new free variable is instantiated, it is assigned to the innermost closure active at run time.  Example:

def foo
  result = 0
  (0..5).each do |n|
    result = n
  end
end

Here exactly one result variable is instantiated across the entire method, and after the each loop terminates, its value is 5. However, in this example:

def foo
  (0..5).each do |n|
    result = n
  end
end


the scope of the result variable is limited to the each block, because --- and this is important --- Ruby converts this block to a closure when the each method is invoked (see above). That is important because it explains why this other, semantically equivalent, code behaves differently:

def foo
  n = 0
  while n < 5 do
    n = n + 1
    result = n
  end
end

See the difference?  Because the block in the while loop isn't a closure, the result variable here belongs to the scope of the foo method. It is like the first example, except that in that case we had to force the variable's scope by deliberately instantiating it at the method level. That's not necessary here because the while block isn't a closure; only the each block is.

If you are anything like me, at this point you have already begun drinking heavily.  Byzantine scoping rules like these are just a recipe for disaster.

Matz deserves a lot of credit for recognizing how bad this is.  I have not had a chance to review what's happening with Ruby2, but the changes Matz describes in these slides look like a considerable improvement from the current state of affairs.

Anyway

Despite all this I can't really say that I dislike Ruby.  I've been working in Ruby on Rails for only a few months, and have not really delved deeply into what the language has to offer, but I find a lot of its self-redefinition features really encouraging and intriguing.  I can see that Matz has tried hard to strike a good balance between conceptual elegance and programming expressiveness, and that's a difficult line to walk.  What makes me unhappy is where the language appears to violate the principle of least surprise; if issues like these can be remedied effectively, it will make Ruby substantially more appealing to hackers like me.
ext_86356: (Default)

[identity profile] qwrrty.livejournal.com 2008-03-10 01:50 pm (UTC)(link)
The last functional (which I assume you mean in contrast to object oriented) language I used was C

Well, no, what I mean by "functional language" is, well, a functional programming language (http://en.wikipedia.org/wiki/Functional_programming). Languages like C and Pascal are usually described as "procedural" or "imperative" (http://en.wikipedia.org/wiki/Imperative_programming) languages. The world is not divided into "Java" and "everything else," much though Sun may want us to think so. :-)

And in Java and other OO languages, this is a non-issue...you'd just operate on your object using whatever methods it provided to do so.

I'm not sure I get that it's a non-issue. My ignorance of Java is showing here, but it seems as if Java 2's Array sort method (http://java.sun.com/j2se/1.4.2/docs/api/java/util/Arrays.html#sort(java.lang.Object[],%20java.util.Comparator)) can take a "Comparator" as an argument, which looks like how you might implement the example I gave here. It's not clear to me exactly what a Comparator is (the docs seem to say that it's an "interface"), but the point is that the object itself doesn't necessarily know how you might want to sort it at any given moment; you have to provide a different thing (the comparator) that has that knowledge.

So...why DOESN'T Ruby allow it?

Didn't you read my post? :-) Doing so would interfere with Ruby's syntactic sugar that allows you to call methods without parentheses.

[identity profile] dbang.livejournal.com 2008-03-10 02:17 pm (UTC)(link)
Comparator. Blech. Very un-javalike.

The reason I said it is a non-issue is because there are other more typical ways to handle this. Not that you *can't* have a class that exists solely as a reference point to methods, but that more often you would see a class that defines a method so that the object knows how to compare itself to something else. (ie: the object would implement the Comparable interface (http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html)).

[identity profile] khedron.livejournal.com 2008-03-10 04:28 pm (UTC)(link)
Un-Java-like? How so? The ability to define a local instance of a Comparator which understands local state, which you can pass off to a sorting function to sort things in a customized way, is very Java. That's been around since the beginning.

You're certainly right, there are other ways to do it. But this lets you handle arbitrary stuff.

Where C passes function pointers, Java passes objects implementing an expected interface, which may or may not have been defined on the fly. Java anonymous classes aren't quite as good as Lisp closures, mostly because they can only close over "final" variables, but they add a measure of convenience (and reduce, for once, the amount of code you have to type to get that functionality).