Answer
module BlankBinding def self.for(object) @object = object create end def self.create @object.instance_eval{ binding } end end
Description
To get binding without local variables, you must call binding in a scope without any of them. A method call resets local variables, so we must do this. However, if we do something like this:
def blank_binding_for(obj) obj.instance_eval{ binding } end
... the resulting binding will have a local variable obj . You can hide this fact like this:
def blank_binding_for(_) _.instance_eval{ binding }.tap{ |b| b.eval("_=nil") } end
... but this only removes the value of the local variable. (There is no remove_local_variable method in Ruby right now.) This is enough if you intend to use the binding in a place like IRB or ripl , where the variable _ is set after each evaluation and thus works according to your shadow.
However, as shown in the answer at the top, there is another way to pass the value to the method and through an instance variable (either a class variable or a global variable). Since we use instance_eval to offset self to our object, any instance variables that we create to invoke the method will not be available in the binding.
source share