rubyirbproc-object

proc changing class in irb


Just when I thought I had my head wrapped around procs & lambdas this happens...

irb> x = Proc.new{|name| "Hello #{name}"}
irb> x.class #=> Proc
irb> x.call("Bob") #=> "Hello Bob"
irb> x.class #=> String
irb> x #=> "Bob"

Why is x changing its class when called?

What am I misunderstanding and/or doing wrong here?


Solution

  • First of all, there's a syntax error in your code, so I'm assuming you mean x = Proc.new {|name| "Hello #{name}"} instead of x = Proc.new (|name| "Hello #{name}"}.

    Second, when I run your example code I don't get that behavior.

    However, if the name variable were to be named the same as the variable name where you store the proc (x in your example), and you were using a ruby version prior to 1.9, you will get this behavior.

    Here's an example of that (I use x as the name of the block variable, and this is ruby 1.8.7):

    >> x = Proc.new {|x| "Hello #{x}"}
    => #<Proc:0x00000001013335b8@(irb):1>
    >> x.class
    => Proc
    >> x.call("Bob")
    => "Hello Bob"
    >> x.class
    => String
    >> x
    => "Bob"
    

    The reason that happens is because you can overwrite a variable defined outside of the current scope in ruby pre 1.9. In ruby 1.9 this behavior is called shadowing, and is described here.