Is it possible to execute a proc within the context of another object?
I know that normally you'd do proc.call(foo), and then the block should define a parameter. I was wondering though whether I could get "self" to bind to foo so that it's not necessary to have a block parameter.
proc = Proc.new { self.hello } class Foo def hello puts "Hello!" end end foo = Foo.new # How can proc be executed within the context of foo # such that it outputs the string "Hello"? proc.call
To keep track of the current scope, Ruby uses bindings, which encapsulate the execution context at each position in the code. The binding method returns a Binding object which describes the bindings at the current position.
A Proc object is an encapsulation of a block of code, which can be stored in a local variable, passed to a method or another Proc, and can be called. Proc is an essential concept in Ruby and a core of its functional programming features.
foo.instance_eval &proc
instance_eval
can take a block instead of a string, and the &
operator turns the proc into a block for use with the method call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With