Making Ruby Look Like Javascript

Yeah, yeah, but your scientists were so preoccupied with whether or not they could that they didn't stop to think if they should. - Dr. Ian Malcolm, Jurassic park

Inspired by this tweet, I was wondering tonight to what degree I could make ruby look like other languages. Please don't anyone ever actually do this.

So far I've come up with three tactics:

  1. Semicolons are already valid in ruby.
  2. var foo = can be accomplished by a dummy var function.
  3. function(x){ just looks like the start of some block syntax.

Put it all together and you might be able to confuse a JS programmer for a second or two:

var sum = function(:a, :b) {
  a + b;
console.log[ sum[ 3, 4 ] ];
# Prints "7"

Here's the code to make it work:

require 'ostruct'

def var(_)

console = (->(s){puts s}))

def function(*args, &block)
  klass = { attr_accessor *args } { |*arg_values|
    obj = {|arg, arg_value| obj.send(:"#{arg}=", arg_value) }

The only interesting bit is the function definition. It takes in a block and returns a function (a proc) that, when called, executes the block. It injects the specified variables into the block by sticking them on a new object then evaluating the block with that object as context. There's probably a better way to do that, but this was all I could find. Everything else would have required declaring the function with a very un-javascript-like function(:a, :b) { |a, b| ....