1. July, 2007
1. July, 2007
in by Michael Neumann

In Ruby really everything is an expression (as well as an object), while in Javascript there is a distinction between statements and expressions. For example "if" or "while" are statements. In Ruby you can write for example:

a = if a > 0 then 1 else 0 end

Which is equivalent in Javascript with:

a = a > 0 ? 1 : 0

The above is of course valid Ruby code, too. So if you want to write a Ruby to Javascript translator, use "?:" instead of "if". But how to map "while" to an expression in Javascript? Well, the easiest approach is using a function:

while(cond) { stmts; }

// maps to

(function(){ 
  while(cond) { stmts; }
})()

That makes it very easy to translate between Ruby and Javascript. The whole method body is one expression, so the Ruby code:

def meth()
  stmt1
  stmt2
  stmt3
end

maps to the following Javascript:

function() {
  return (stmt1, stmt2, stmt3);
}

where each statement (stmt1, stmt2, stmt3) is translated into an expression.

Of course functions have some overhead.

What I've not thought about is "return" and "throw", which are statements as well, so that the approach given above does not work for them.