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.

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(_)
end

console = OpenStruct.new(log: (->(s){puts s}))

def function(*args, &block)
  klass = Class.new { attr_accessor *args }
  Proc.new { |*arg_values|
    obj = klass.new
    args.zip(arg_values).each {|arg, arg_value| obj.send(:"#{arg}=", arg_value) }
    obj.instance_eval(&block)
  }
end

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| ....