Wednesday, March 04, 2009

Itt: Lies

People often talk about how readable Ruby is, how a person who's never seen a computer program could just about understand what's happening. After all, the clean syntax is what initially attracted me to Ruby. As it turns out though, that's only true if you're writing in the imperative.

For instance, this is how you'd be expected to write a summation function in something like Java:

def summation1 (n)
  if n == 0
    return 0
  else
    return n + summation1(n-1)
  end
end

puts summation1(3) #Outputs 6


That's readable even to the layperson right? Except spoilers: nobody actually uses Ruby that way. Let's try something else then:

def summation2 (n)
  a = Array.new
  n.times {|x| a << x)
  return a.inject {|x,y| x+y }
end

puts summation2(3) #Outputs 6


Okay, I admit that was a bit contrived. But you can see where this is leading:

summation3 = lambda {|x| (1..x).inject {|x,y| x+y }}
p summation3[3] #Outputs 6


What. Did I get hit by the Haskell train or something?

Basically what I'm trying to say is, Ruby is a very concise and elegant language. But with so many shortcuts built in, its general readability does suffer. At least for people not familiar with this kind of functionality. That said, condensing 8 lines of code into 2 only makes me enjoy Ruby more, not less.

Note: That is not a typo in example 3, there is indeed a shortcut for puts. People don't tend to use it so much though, or at least I don't.

No comments: