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
iglobal scope, ruby code doesn't leaki@ all, local innermost block. - there no function call operator in ruby, instead use method
proc#call, ecmascript has (function.prototype.call). - you use
forloop, whereas ruby code uses method onintegeriteration. kernel#putswrite implicitly whatever have defined default output stream, whereas proposed ecmascript solution explicitly write console.selflexically bound in ruby,thisdynamically bound function object in ecmascript, unless use arrow function literal, bindsthislexixally.
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
forloop (onlyfor … initerator), closest thingwhileloop. - ruby doesn't have call operator,
.()syntactic sugarcallmethod. thisin nested function expression dynamically bound,selfin ruby lexical.
Comments
Post a Comment