Home Play Pinja Bobbity flop

A blog about Ruby, Rails and other Tech. Mostly.

Back to blog

1st Oct 2007, 12:02pm
Why Ruby is not my favourite programming language

Actually it is my favourite. But the title comes from this article (which itself was inspired and copied from the famous paper about pascal by Brian Kernighan).

On with business though - Ruby has some serious wrinkles that produce counter-intuative and plain strange behaviour. One might say that they violate the Principle of Least Surprise. But POLS is somewhat personal - surprising to whom? (just me maybe!)

Surprising result #1

b=1
=> 1
a if a=b
NameError: undefined local variable or method `a' for main:Object
        from (irb):2

This is odd indeed. It seems that the Ruby parser thinks that a is a method at the beginning of the line. But when it parses a=b it will know (and remember) that it is a variable. However, when the condition passes and it comes to execute 'a', it does not apply its new found knowledge about the nature of a - it still goes for the method. And hence the error.

Surprising result #2

c=1 unless defined? c
=> nil
c
=> nil

This is a bit easier to explain. Once the parser has seen c=1 it enters c in the symbol table, it knows that c exists as a variable. Hence it is defined (as nil). So c=1 is never executed.

Surprising result #3

class A
  attr_accessor :a
  def b
    @a=0
    x=a
    a=x+1
    puts("a is #{a}")
    puts("@a is #{@a}")
  end
end
=> nil
c = A.new
=> #<A:0x32fb7c>
c.b
a is 1
@a is 0

No mystery here really - it's a nice gotcha though - a= does not call self.a=, it just assigns a local variable. It is just a little confusing unless you think carefully.

Surprising result #4

[0.0, 1/0.0].sort
=> [0.0, Infinity]
[0.0, 0/0.0].sort
ArgumentError: comparison of Float with Float failed

Thanks to Evan Weaver for pointing this out to me. This is due to 0/0.0 returning the value NaN (as opposed to 1/0.0 which returns Infinity). And the comparison with NaN by sort gives the strange error message.

Let me know if you spot any more oddities.


Back to blog