"break" from a block and a proc object used in block position

Discussion in 'Ruby' started by Wolfgang Nádasi-Donner, May 31, 2007.

  1. Hi!

    In german ruby-forum we had a question which ends up in unclear situations. The
    following code:

    ----- Code -----
    def useblk1
    puts "block (useblk1) returns '#{yield}'"
    99
    end
    puts "useblk1 returns '#{useblk1 {break 42}}'"

    def useblk2(&blk)
    puts "block (useblk2) returns '#{blk.call}'"
    99
    end
    puts "useblk2 returns '#{useblk2 {break 42}}'"

    def useblk3
    puts "block (useblk3) returns '#{yield}'"
    99
    end
    puts "useblk3 returns '#{useblk3(&lambda{break 42})}'" rescue puts "useblk3
    error: #$!"

    def useblk4
    puts "block (useblk4) returns '#{yield}'"
    99
    end
    puts "useblk4 returns '#{useblk4(&Proc.new{break 42})}'" rescue puts "useblk4
    error: #$!"
    ----- End of Code -----

    results under Ruby 1.8.6 (OneClickInstaller-186-25) in:

    ----- Result Ruby 1.8.6 -----
    useblk1 returns '42'
    useblk2 returns '42'
    useblk3 error: break from proc-closure
    useblk4 error: break from proc-closure
    ----- End of Result -----

    Which surprises me. When I read "PickAxe2" all should return from the method
    with the value presented by "break".

    When I run this Program with Ruby 1.9 (MSYS/MinGW build on Windows2000,
    2007-05-15 patchlevel 0) the result is the following:

    ----- Result Ruby 1.9 -----
    useblk1 returns '42'
    block (useblk2) returns '42'
    useblk2 returns '99'
    useblk3 returns '42'
    useblk4 returns '42'
    ----- End of Result -----

    Here I'm confused by the result of "useblk2", but the rest is clear for me.

    Did I make an error? - Are there Errors in 1.8.6? - Are there Errors in 1.9? - ???

    I must admit that I am confused...

    Wolfgang Nádasi-Donner
     
    Wolfgang Nádasi-Donner, May 31, 2007
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. David Lozzi
    Replies:
    3
    Views:
    1,951
    David Lozzi
    Jun 1, 2005
  2. NevilleDNZ
    Replies:
    9
    Views:
    454
    NevilleDNZ
    Aug 16, 2006
  3. Jean-Hugues ROBERT

    Why no Proc##[]=() ? Why no Proc##replace() ?

    Jean-Hugues ROBERT, May 1, 2004, in forum: Ruby
    Replies:
    14
    Views:
    301
    Jean-Hugues ROBERT
    May 5, 2004
  4. Phil Tomson
    Replies:
    0
    Views:
    117
    Phil Tomson
    Jan 15, 2006
  5. Minkoo Seo

    Proc vs lambda vs proc

    Minkoo Seo, Feb 4, 2007, in forum: Ruby
    Replies:
    19
    Views:
    253
    Brian Candler
    Feb 6, 2007
Loading...

Share This Page