Neat trick - 'with' and unnamed objects + 'with' proposals
eao197
eao197 at intervale.ru
Tue Apr 24 06:42:02 PDT 2007
On Tue, 24 Apr 2007 17:03:07 +0400, Bill Baxter
<dnewsgroup at billbaxter.com> wrote:
> Denis Golovan wrote:
>>> Or perhaps analogous to how constructors are called 'this()' and have a
>>> 'this' pointer, we'd have a 'with' pointer so that the meaning of
>>> 'this' in a class wouldn't be shadowed:
>> +1. That feature is useful sometimes.
>
> You say "is" as if it exists in some other language that you've used?
> Does it? And if so what's the syntax?
Such behaviour can easily be implemented in Ruby. This is very simple
demonstration:
# Just a demo class.
class Demo
attr_reader :shown
attr_reader :focused
end
# Yet another demo class.
class AnotherDemo
attr_reader :title
end
# A globe function to be called with 'with' keyword.
def some_global_function( obj )
p obj
end
# This is implementation of 'with'.
def with( obj, &blk )
# 1: introduce a new method 'with' into object 'obj'.
class <<obj
def with; self; end
end
# 2: run the specified block on 'obj' context.
# Because now 'obj' has method 'with' it can be
# called from block body.
begin
obj.instance_eval &blk
ensure
# 3: method 'with' no more needed.
class <<obj
remove_method( :with )
end
end
obj
end
# This is usage of 'with'
d = with( Demo.new ) {
@shown = false
@focused = true
# Content of new object of class Demo must be shown here.
some_global_function( with )
}
a = with( AnotherDemo.new ) {
@title = 'Hello, World'
# Content of new object of class AnotherDemo must be shown here.
some_global_function( with )
}
# Simple debug output.
puts "d: shown: #{d.shown}, focused: #{d.focused}"
puts "a: title: #{a.title}"
That program prints:
#<Demo:0x2c7d448 @shown=false, @focused=true>
#<AnotherDemo:0x2c7d3f8 @title="Hello, World">
d: shown: false, focused: true
a: title: Hello, World
Such implementation of 'with' assumes that obj hasn't method 'with'. But
this limitation can be removed via aliasing.
--
Regards,
Yauheni Akhotnikau
More information about the Digitalmars-d
mailing list