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?
First of all, there’s a syntax error in your code, so I’m assuming you mean
x = Proc.new {|name| "Hello #{name}"}instead ofx = Proc.new (|name| "Hello #{name}"}.Second, when I run your example code I don’t get that behavior.
However, if the
namevariable were to be named the same as the variable name where you store the proc (xin 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
xas the name of the block variable, and this is ruby 1.8.7):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.