top | item 29204401

(no title)

didroe | 4 years ago

The main advantages of Ruby blocks over that approach are:

- they have special control flow that interacts with the method call or surrounding function. ie. calling `break` in `something` can early return from `someMethod`, or calling `return` will return from the function containing the `someMethod` call (blocks use `next` to return from them)

- due to using separate syntax / being a separate language construct, there is far better ergonomics in the presence of vargs or default values

Take this contrived example for instance:

  def some_method(a = 42)
      b = yield
      puts "Hey #{a} #{b}"
  end

  some_method do
    break
  end

In JS you would have to something horrible like this:

  const breakSomeMethod = {}; // Could alternatively use an exception

  function someMethod(one, two) {
    var f, a;
    if (typeof one == 'function') {
      f = one;
      a = 42;
    } else {
      a = one;
      f = two;
    }

    var b = f();
    if (b === breakSomeMethod) {
      return;
    }

    console.log(`Hey ${a} ${b}`)
  }

  someMethod(() => breakSomeMethod);

discuss

order

No comments yet.