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 leaki
@ 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 oninteger
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, bindsthis
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 (onlyfor … in
iterator), closest thingwhile
loop. - ruby doesn't have call operator,
.()
syntactic sugarcall
method. this
in nested function expression dynamically bound,self
in ruby lexical.
Comments
Post a Comment