0

Im my real code I have bunch or Procs that need access to multiple out-of-the-proc variables. It will be very helpful for me if I have not to take care in which order the variables and procs are defined, as far they are defined in the moment the Proc is executed.

For example:

my_proc = Proc.new { puts name }
name = "Jacinto"
my_proc.call # => undefined local variable or method `name' for main:Object (NameError)

This works:

name = "Jacinto"
my_proc = Proc.new { puts name }
my_proc.call # => Jacinto

This also works:

name = nil
my_proc = Proc.new { puts name }
name = "Jacinto"
my_proc.call # => Jacinto

But as I said for code readability and comfortability I want to be able to define the Proc before the variable is defined. How can I solve this?

(In my mind this should be totally possible since the code in the Proc has a delayed execution and when the execution is triggered the variable is there. )

fguillen
  • 36,125
  • 23
  • 149
  • 210

1 Answers1

-1

You can add it as a parameter:

my_proc = Proc.new { |name| puts name }
name = "Jacinto"
my_proc.call(name) # => "Jacinto"
SandeliusME
  • 802
  • 1
  • 10
  • 19