I propose that the following method be added to Ruby:
class Binding
def eval str
Kernel.eval str, self
end
end
This makes eval'ing code in a given binding more OO. So code like
eval "myvar = 120", binding
becomes:
binding.eval "myvar"
which is more in keeping with the general Ruby way, IMHO.
Bill Atkins
Hi,
For sure the Binding class would deserve some methods, it has
none as of today !
class Binding
# Evaluate a Ruby source code string in the binding context
def eval( str ) Kernel.eval( str, self) end
# Returns the self in the binding context
def self(); eval( "self") end
# Returns the local variables defined in the binding context
def local_variables(); eval( "local_variables") end
# Returns the Method that was active, if any, when the binding was created
def method() ...???...
# Returns the Proc that was active, if any, when the binding was created
def proc() ... ??? ...
# Returns the call stack, same format as Kernel##caller()
def caller( skip = 0 ); eval( "caller( #{skip})") end
# Returns the value of some rvalue
def [](x); eval( x.to_s()) end
# Set the value of some lvalue
def []=(l,v); eval( "proc {|v| #{l} = v").call( v) end
# Returns the nature of something, nil if that thing is not defined.
def defined?(x); eval( "defined? #{x}") end
end
Most methods could be defined for class Proc too I suppose, but I would
prefer a class Proc; def binding() eval( "binding", self) end end
I am adding this to my rcr.rb (the file where I put extensions to standard
classes). Thanks !
Yours,
Jean-Hugues