On Tue, Mar 5, 2013 at 8:14 PM, Eric Christopherson
<[email protected]> wrote:

> `break val` also exits from a block, returning val, but in some cases
> also exits from the method calling the block.

I'd rephrase that to "usually it exits from the method which invoked
the block" (lines 23 and 24 below seem to me the most usual use case).

> I wrote a test case for
> this on my work computer, but I don't have access to it here; but I
> seem to recall that break in a lambda simply exits the block, while
> break in a proc exits the method. (If you create the proc by passing a
> block to Proc.new, and then pass that proc to another method, which
> calls it, break will raise a LocalJumpError, since the original stack
> frame of Proc.new no longer exists.)

Yes, you are right:

irb(main):013:0> def f
irb(main):014:1> p "enter"
irb(main):015:1> p yield 1
irb(main):016:1> p yield 2
irb(main):017:1> p yield 3
irb(main):018:1> ensure
irb(main):019:1* p "exit"
irb(main):020:1> end
=> nil
irb(main):021:0> f {|i| i * 10}
"enter"
10
20
30
"exit"
=> 30

"next":

irb(main):022:0> f {|i| next i * 10 if i == 1; i}
"enter"
10
2
3
"exit"
=> 3

"break":

irb(main):023:0> f {|i| break i * 10 if i == 1; i}
"enter"
"exit"
=> 10
irb(main):024:0> f {|i| break i * 10 if i == 2; i}
"enter"
1
"exit"
=> 20


"local" break:

irb(main):028:0> f = lambda {|i| break i * 10 if i == 2; p i}
=> #<Proc:0x8025260c@(irb):28 (lambda)>
irb(main):029:0> 5.times &f
0
1
3
4
=> 5
irb(main):030:0> f = lambda {|i| next i * 10 if i == 2; p i}
=> #<Proc:0x8022ed10@(irb):30 (lambda)>
irb(main):031:0> 5.times &f
0
1
3
4
=> 5

Proc:

irb(main):032:0> f = Proc.new {|i| next i * 10 if i == 2; p i}
=> #<Proc:0x801dc588@(irb):32>
irb(main):033:0> 5.times &f
0
1
3
4
=> 5
irb(main):034:0> f = Proc.new {|i| break i * 10 if i == 2; p i}
=> #<Proc:0x801b76d4@(irb):34>
irb(main):035:0> 5.times &f
0
1
LocalJumpError: break from proc-closure
        from (irb):34:in `block in irb_binding'
        from (irb):35:in `times'
        from (irb):35
        from /usr/bin/irb:12:in `<main>'

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

-- 
[email protected] | 
https://groups.google.com/d/forum/ruby-talk-google?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"ruby-talk-google" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to