leynos: (Default)
leynos ([personal profile] leynos) wrote2011-05-10 11:21 pm
Entry tags:

How Ruby Is Not JavaScript

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.