Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding of Procs

Tags:

ruby

binding

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 
like image 279
Jim Soho Avatar asked Feb 08 '09 07:02

Jim Soho


People also ask

What is binding in Ruby?

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.

What are Ruby procs?

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.


1 Answers

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.

like image 182
Chuck Avatar answered Oct 12 '22 11:10

Chuck