Links
Tags
apache
armenia
books
bsd
c
c++
chips
cinema
concurrency
cooking
database
dragonfly
erlang
filesystem
freebsd
fun
hardware
java
javascript
json
languages
linux
lyric
mac_osx
mail
math
misc
music
personal
poems
presentation
programming
python
references
ruby
rubyjs
scm
software
spiking_neural_net
study
sysadm
sysarch
technology
testing
travel
virtualization
web
wee
windows
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.