J
Jean-Hugues ROBERT
Hi,
I am coining a Pointer class in Ruby. Kind of a C pointer, more
like a C++ smart pointer actually. Should work for any lvalue.
Any previous art ?
Any way to avoid evil eval ?
Yours,
Jean-Hugues
PS: thanks to http://onestepback.org/index.cgi/Tech/Ruby/RubyBindings.rdoc
class Pointer
attr_accessor :lvalue
attr_reader :binding
attr_reader :getter
attr_reader :setter
def initialize( &block ) ref( &block) end
def ref( &block )
@binding = block.binding()
@lvalue = block.call()
@getter = eval( "proc { #@lvalue }", block)
@setter = eval( "proc { |v| #@lvalue = v }", block)
end
def []() @getter.call() end
def []=( new_value ) @setter.call( new_value); end
def to_s() self[].to_s() end
def inspect() "<Pointer #{lvalue()}>#{self[].inspect()}" end
end
ptr = Pointer.new {"$A"}
ptr[] = "Hello"
ptr[] += ", world."
p "@{$A} -- #{ptr}"
b = nil
ptr.ref{ :b}
ptr[] = "This is Ruby."
p b
p ptr
ptr.ref{ :ENV}
p ENV["USERNAME"]
ptr[]["USERNAME"] = "Ruby"
p ENV["USERNAME"]
p ptr.binding()
I am coining a Pointer class in Ruby. Kind of a C pointer, more
like a C++ smart pointer actually. Should work for any lvalue.
Any previous art ?
Any way to avoid evil eval ?
Yours,
Jean-Hugues
PS: thanks to http://onestepback.org/index.cgi/Tech/Ruby/RubyBindings.rdoc
class Pointer
attr_accessor :lvalue
attr_reader :binding
attr_reader :getter
attr_reader :setter
def initialize( &block ) ref( &block) end
def ref( &block )
@binding = block.binding()
@lvalue = block.call()
@getter = eval( "proc { #@lvalue }", block)
@setter = eval( "proc { |v| #@lvalue = v }", block)
end
def []() @getter.call() end
def []=( new_value ) @setter.call( new_value); end
def to_s() self[].to_s() end
def inspect() "<Pointer #{lvalue()}>#{self[].inspect()}" end
end
ptr = Pointer.new {"$A"}
ptr[] = "Hello"
ptr[] += ", world."
p "@{$A} -- #{ptr}"
b = nil
ptr.ref{ :b}
ptr[] = "This is Ruby."
p b
p ptr
ptr.ref{ :ENV}
p ENV["USERNAME"]
ptr[]["USERNAME"] = "Ruby"
p ENV["USERNAME"]
p ptr.binding()