How Ruby Is Not JavaScript
May. 10th, 2011 11:21 pm![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
Learning two languages simultaneously sometimes gets one confused. The way Ruby and JavaScript treat function declarations is an interesting example:
Run the JavaScript version:
The second line of output is where it gets weird depending upon your point of view.
The JavaScript person is likely of the opinion that "function test() { ... }" should be equivalent to "var test = function() { ... };", and so it should be enclosed by the anonymous function declaration. Hence the output of "bar" is as expected.
The Rubyist on the other hand probably feels that the call to test() should be considered a lookup within the current scope for a corresponding method declaration. Since, where the block is yielded to, the declaration of test() returns "foo", they are not surprised either.
It all make for some interesting moments of uncertainty.
Ruby:def myfun() raaa = "nope\n" def test print "foo\n" end yield end def test print "bar\n" end raaa = "eep\n" myfun do print raaa test end |
JavaScript:function myfun(m) { var raaa = "nope"; function test() { print("foo"); } m(); } function test() { print("bar"); } var raaa = "eep"; myfun(function() { print(raaa); test(); }); |
eep barAnd the Ruby version:
eep fooIn both cases, the variable "raaa" is enclosed by the block/anonymous function passed to myfun(). This is as one would expect for most dynamic languages with closures.
The second line of output is where it gets weird depending upon your point of view.
The JavaScript person is likely of the opinion that "function test() { ... }" should be equivalent to "var test = function() { ... };", and so it should be enclosed by the anonymous function declaration. Hence the output of "bar" is as expected.
The Rubyist on the other hand probably feels that the call to test() should be considered a lookup within the current scope for a corresponding method declaration. Since, where the block is yielded to, the declaration of test() returns "foo", they are not surprised either.
It all make for some interesting moments of uncertainty.