X
xiMera
Hi all,
Ruby does not support named parameter for now as all of you know.
There is really three solutions for this
* hash as parameter
* class as parameter
* bindings
Hash parameters:
def do_some( params )
a = params[ :a ]
b = params[ :b ]
end
do_some :a => 1, :b =>2
Class parameters (ugly, written in couple minutes)
class A
def metaclass
class << self; self; end
end
def set_var( name, val )
eval "@#{name} = val", binding
self.metaclass.send( :define_method, name ) do
eval "@#{name}"
end
end
def set_vars( params )
params.each{ |key,val| self.set_var( key, val ) }
end
end
def do_some( params )
a = params.a
b = params.b
end
A.new
a.set_vars( :a => 1. :b =>2 )
do_some a
Bindings way:
def do_block( &block )
eval "a=1", block.binding
eval "b=2", block.binding
end
do_block( params ){
a = eval 'a'
b = eval 'b'
}
As we can see there is overtyping in all cases. We always need to map
incoming variables into locals or write ugly accessor every time.
So My question is:
Is there any way to set local variables for blocks outside of block
scope?
IMHO nice solution will looks like this:
def do_some( &block )
block.binding.set_var( 'a', 1 )
block.binding.set_var( 'b', 2 )
block.call
end
do_some{
puts a
puts b
}
Ruby does not support named parameter for now as all of you know.
There is really three solutions for this
* hash as parameter
* class as parameter
* bindings
Hash parameters:
def do_some( params )
a = params[ :a ]
b = params[ :b ]
end
do_some :a => 1, :b =>2
Class parameters (ugly, written in couple minutes)
class A
def metaclass
class << self; self; end
end
def set_var( name, val )
eval "@#{name} = val", binding
self.metaclass.send( :define_method, name ) do
eval "@#{name}"
end
end
def set_vars( params )
params.each{ |key,val| self.set_var( key, val ) }
end
end
def do_some( params )
a = params.a
b = params.b
end
A.new
a.set_vars( :a => 1. :b =>2 )
do_some a
Bindings way:
def do_block( &block )
eval "a=1", block.binding
eval "b=2", block.binding
end
do_block( params ){
a = eval 'a'
b = eval 'b'
}
As we can see there is overtyping in all cases. We always need to map
incoming variables into locals or write ugly accessor every time.
So My question is:
Is there any way to set local variables for blocks outside of block
scope?
IMHO nice solution will looks like this:
def do_some( &block )
block.binding.set_var( 'a', 1 )
block.binding.set_var( 'b', 2 )
block.call
end
do_some{
puts a
puts b
}