How is Proc object created from a block?

Discussion in 'Ruby' started by Phil Tomson, Jan 15, 2006.

  1. Phil Tomson

    Phil Tomson Guest

    So let's say you have a method that takes a block, like so:

    def if?(cond, &b)
    puts "b is a: #{b.class}"
    if cond
    b.call
    end
    cond
    end

    call it:

    if?(true) { puts "yes!" }


    We know that "b is a: Proc" will be printed" (along with yes!) so we know that
    when we pass a block into a method using the '&' that it 'magically' becomes a
    Proc object.

    But how exactly does that happen?

    I tried modifying the Proc class to find out (thinking that Proc.new must be
    called at some point):

    class Proc
    alias_method :eek:ld_init, :initialize
    def initialize &b
    puts "Proc::b.class is: #{b.class}"
    old_init &b
    end
    class << self
    alias_method :eek:ld_new, :new
    def new &b
    puts "Proc::new"
    old_new &b
    end
    end
    end

    if?(true) {puts "yes!"}
    #=>b is a: Proc
    #=>yes!

    It doesn't look like Proc.new was called... So how was the block transformed
    into a Proc object?

    A bit of background: I'm trying to put some sort of @level class instance var
    in Proc so I can determine how deeply nested in Proc's I am at any given
    point:

    if?(cond){ #level==1
    if?(cond2) { #level==2
    if?(cond3) { #level==3
    }
    }
    }

    To do that I figured I'd need to do it in Proc.new, but it doesn't seem to get
    called...

    Phil
     
    Phil Tomson, Jan 15, 2006
    #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,949
    David Lozzi
    Jun 1, 2005
  2. NevilleDNZ
    Replies:
    9
    Views:
    452
    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:
    299
    Jean-Hugues ROBERT
    May 5, 2004
  4. Minkoo Seo

    Proc vs lambda vs proc

    Minkoo Seo, Feb 4, 2007, in forum: Ruby
    Replies:
    19
    Views:
    249
    Brian Candler
    Feb 6, 2007
  5. Wolfgang Nádasi-Donner
    Replies:
    0
    Views:
    126
    Wolfgang Nádasi-Donner
    May 31, 2007
Loading...

Share This Page