leynos: (Default)
[personal profile] leynos
Learning two languages simultaneously sometimes gets one confused. The way Ruby and JavaScript treat function declarations is an interesting example:

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();
});

Run the JavaScript version:
eep
bar
And the Ruby version:
eep
foo
In 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.

From:
Anonymous( )Anonymous This account has disabled anonymous posting.
OpenID( )OpenID You can comment on this post while signed in with an account from many other sites, once you have confirmed your email address. Sign in using OpenID.
User
Account name:
Password:
If you don't have an account you can create one now.
Subject:
HTML doesn't work in the subject.

Message:

 
Notice: This account is set to log the IP addresses of everyone who comments.
Links will be displayed as unclickable URLs to help prevent spam.

Profile

leynos: (Default)
leynos

January 2015

S M T W T F S
    123
456 78910
11121314151617
18192021222324
25262728293031

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Sep. 21st, 2017 05:39 pm
Powered by Dreamwidth Studios