How Close Can JS Get To Ruby?
Along time ago I wrote a post about how closely JavaScript could match Ruby Syntax (without parsing a Ruby string of course). Even though Ruby is generally very expressive, it is possible to get very close with modern JS features. It also illustrates a few interesting parts of JavaScript. Firstly, here is a Fibanacci function in Ruby:
def fib(n) if (n < 2) return n end fib(n - 1) + fib(n - 2) end puts fib 0 puts fib 1 puts fib 2 puts fib 11 puts fib 17
And here is the JS version:
def(fib, (n) => { if (n < 2) { return n } return fib(n - 1) + fib(n - 2) }) puts. fib(0) puts. fib(1) puts. fib(2) puts. fib(11) puts. fib(17)
In order to accomplish the closest look, best practices such as semicolon insertion and avoiding globals were ignored here. Here is the setup with comments:
// Symbols can be used as literal values. To reassign with the global, this must set globally with // no prefix. i.e. this is not strict mode compliant fib = Symbol('fib'); const puts = {}; function def(name, callback) { // This will always be in the format Symbol('string') for all strings const symbolString = String(name).slice(7, -1); // Make the given function accessible anywhere global[symbolString] = callback; // The ... take all the arguments and put them into the variable beside them puts[symbolString] = function(...args) { const result = callback.apply(this, args); console.log(result); }; };
The def takes care of all the setup except puts. To reduce syntax a function could be added to puts and JS accepts whitespace after object properties. Unfortunately, only string object properties are allowed (and not numbers), so the periods could not be used further.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2017/ruby.js











