javascript - Are these 2 lines of code the same ? JS vs Ruby -


in ruby:

->  { 10.times {|i| puts i} }.call 

javascript:

(function (){     (i = 0; i<10; i++){         console.log(i);     } })() 

im coming js background , peaked interest when learning lambdas , procs says function without names called. reminded me of anonymous functions or iife in javascript.

are these 2 examples same? if not difference ?

these 2 lines different in every aspect.

the closest ecmascript equivalent ruby snippet:

-> { 10.times {|i| puts i} }.call 

would this:

(() => { 10.times(i => puts(i)) }).call()

unfortunately, numbers can't have methods in ecmascript, have resort this:

(() => { times(10, => puts(i)) }).call()

obviously, in order work, need add ruby library support code:

(() => { times(10, => puts(i)) }).call()    function times(i, f) { if (i-- === 0) return; else { times(i, f); f(i) }}  function puts(s) { console.log(s) }

that's still not alike original ruby semantics, closer proposal:

  • your proposal leaks i global scope, ruby code doesn't leak i @ all, local innermost block.
  • there no function call operator in ruby, instead use method proc#call, ecmascript has (function.prototype.call).
  • you use for loop, whereas ruby code uses method on integer iteration.
  • kernel#puts write implicitly whatever have defined default output stream, whereas proposed ecmascript solution explicitly write console.
  • self lexically bound in ruby, this dynamically bound function object in ecmascript, unless use arrow function literal, binds this lexixally.

on other hand, closest ruby equivalent this:

(function (){      (i = 0; i<10; i++){          console.log(i);      }  })()

would this:

-> { $i = 0; while $i < 10 $stdout.puts($i); $i += 1 end }.() 

again, not 100% equivalent:

  • ruby doesn't have for loop (only for … in iterator), closest thing while loop.
  • ruby doesn't have call operator, .() syntactic sugar call method.
  • this in nested function expression dynamically bound, self in ruby lexical.

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -