Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Ruby's proc block mess really irritates me too, especially when I flip from JS back to Ruby. I just cannot understand why the notion of a block as a distinct entity needs to exist, other than some weird syntactic side effects of Ruby's paren-less method calling.


Here's the reason, it's because of how iteration works in Ruby with "everything is an expression" semantics: http://lucumr.pocoo.org/2012/10/18/such-a-little-thing/

In Ruby iteration is implemented by letting something call a block repeatedly until the end of the iteration. The interpreter provides jump points in order to implement skipping or breaking the iteration. A continue is implemented as a form of jumping to the end of the block, a break is implemented by jumping past the call to the iterator function. Without the return it would be very awkward to return something from the function.Imagine a function that returns the first even item from a list:

    >> def find_even iterable
    >>  iterable.each { |x| return x if x % 2 == 0 }
    >> end
    => nil
    >> find_even [1, 3, 5, 6]
    => 6
Imagine the non-local return was not available, you would have to rewrite it like this:

    >> def find_even iterable
    >>  done = false
    >>  rv = nil
    >>  iterable.each { |x|
    >>   if x % 2 == 0
    >>    done = true
    >>    rv = x
    >>    break
    >>   end
    >>  }
    >>  rv
    >> end
*


Because it is so convenient to be able to return from the outer scope.


I can't recall any occasional where I have done that.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: