My quick hack the other day received a lot of attention, as the graph of visitors shows. I must emphasise that it is just a quick hack, however. It does work to the extent that it can turn a subset of Ruby into working JavaScript, but there’s more to Ruby than just the syntax: non-trivial code is going to fall into the gaps between Ruby and JavaScript semantics rather quickly. JavaScript isn’t as dissimilar from Ruby as some languages, but it’s different enough.

Spike in visitors

In order to get a good simulation of Ruby’s behaviour, we need to build Ruby-like objects in JavaScript. We need inheritance hierarchies and message despatch, and this requires method tables. Coincidentally, this means that we can’t use JavaScript functions directly, but it doesn’t preclude the use of functions altogether. Indeed, JavaScript anonymous function turn out to be very useful.

I’ve started building up the basics of a Ruby runtime in JavaScript, using as much scaffolding from the latter as possible:

  • JS objects to hold Ruby objects and give garbage collection;
  • JS objects for the various look-up tables in Ruby;
  • JS anonymous functions for Ruby method bodies and blocks.

Some special cases in Ruby can be assisted by JS structures:

  • Fixnums can be stored in JS numbers with a hard-coded proxy object for method despatch.
  • JS has null for Ruby’s nil.
  • JS true and false can stand in for their Ruby equivalents.

However, some things won’t work exactly the same:

  • JS strings are Unicode. I don’t intend to change this.
  • There’s no exposed object_id equivalent in JS, so there can’t be one here either.
  • As JS is single-threaded, there won’t be any threads.
  • require and load cannot be implemented in the same way.

There are plenty of other things that I haven’t thought of yet. Despite this, I think that it will be possible to run the majority of straightforward Ruby code. Rails will probably never run in the browser, though!

A few people have asked, ‘why would one want to do this?’ It’s not that I hate JavaScript—I think it’s a fairly decent, if flawed, language. But being able to write front- and back-end code in the same language could be extremely powerful. Algorithms can be shared. Processing can be delegated to the client (remembering, of course, that we can’t trust the results). And, perhaps, more ambitious client-side code will become possible. Most of all, though, I’m just doing it because I can.