R
Robert Klemme
Hi,
it just occurred to me that one sometimes might want to use a proxy
for an instance variable which restricts access in some way.
class Proc
def proxy(meth)
class<<self;self;end.sendalias_method, meth, :call)
self
end
end
class X
def initialize
@e = []
end
def entries
en = lambda {|x| @e << x if x >= 0; en}.proxy<<)
end
end
x = X.new
x.entries << 10 << -12 << 23
p x
You can even use it for things like this:
NULL = lambda {|y| y == 0}.proxy :===
POS = lambda {|y| y > 0}.proxy :===
NEG = lambda {|y| y < 0}.proxy :===
(-2..2).each do |i|
case i
when NEG
puts "#{i} NEG"
when NULL
puts "#{i} NULL"
when POS
puts "#{i} POS"
else
puts "#{i} what?"
end
end
Anybody think this should go into the core? (I'm not religious about the name.)
Kind regards
robert
it just occurred to me that one sometimes might want to use a proxy
for an instance variable which restricts access in some way.
class Proc
def proxy(meth)
class<<self;self;end.sendalias_method, meth, :call)
self
end
end
class X
def initialize
@e = []
end
def entries
en = lambda {|x| @e << x if x >= 0; en}.proxy<<)
end
end
x = X.new
x.entries << 10 << -12 << 23
p x
You can even use it for things like this:
NULL = lambda {|y| y == 0}.proxy :===
POS = lambda {|y| y > 0}.proxy :===
NEG = lambda {|y| y < 0}.proxy :===
(-2..2).each do |i|
case i
when NEG
puts "#{i} NEG"
when NULL
puts "#{i} NULL"
when POS
puts "#{i} POS"
else
puts "#{i} what?"
end
end
Anybody think this should go into the core? (I'm not religious about the name.)
Kind regards
robert