------art_15590_30092135.1204203228526
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-Disposition: inline

On Thu, Feb 28, 2008 at 11:39 PM, S2 <email / fin.ta> wrote:

> I am sure this is a really easy question for most of you, but i was not
> able to find an answer to this, or to understand the difference between
> this two:
>
> $ irb
> irb(main):001:0> a  roc.new {true}
> #<Proc:0xb7cae308@(irb):1>
> irb(main):002:0> b  .call
> true
> irb(main):003:0> a  roc.new {return true}
> #<Proc:0xb7c9f768@(irb):3>
> irb(main):004:0> b  .call
> LocalJumpError: unexpected return
>         from (irb):3
>         from (irb):4:in `call'
>         from (irb):4
>         from :0
>
> why can't a block return something?


Since it isn't a function! :( Now, it can return sometimes -- if it's in a
function defition. And you can see that it could come in handy:

def slow_include arr, el
  arr.each do |e|
    return true if e el
  end
  false
end

p slow_include([1, 2, 3], 3)
p slow_include([1, 2, 3], 4)

Result:

true
false

(of course, you can just use [1, 2, 3].include?(3), but this is for demo)
So, the block there returns from the function, like you'd expect. It's up to
the controlling function (Array#each in this case) to select a return value.
For instance:

[2, 4, 6].map {|q| return q * 2}

What's the expected output? Do we simply get "4" as the entire evaluation?
Remember that Array#map itself is supposed to return a value (the array with
values mapped!). So, blocks can't really return anything - it makes no
sense.

HTH,
Arlen

------art_15590_30092135.1204203228526--