From: Robert Dober Date: 2007-03-07T18:55:47+09:00 Subject: Re: Setting default vales On 3/7/07, Mike wrote: > Hello, > > I want to have some function that will two parameters. First is the > variable name and second is a value. > Inside I will check: > * if the variable is existed I do nothing > * else I assign "value" to variable > > It should be something like this but it is not working. > > def set_default(name, val) > if ! name then > eval "#{name} = #{val}" > end > end > > set_default("b", "2") > puts "b = " + b > > > The first deception will come from this little snippet I am afraid, cat default.rb && echo "--------------" && ruby default.rb # vim: sts=2 sw=2 nu expandtab nowrap: a = 42 def test_a defined? a end p test_a -------------- nil As you can see a is not visible inside the method. Let us try to find a different tool for that # vim: sts=2 sw=2 nu expandtab nowrap: a = 42 test_a = proc { defined? a } p test_a.call -------------- "local-variable" Which is better, we could now try to implement what you want as a proc # vim: sts=2 sw=2 nu expandtab nowrap: a = 42 default = proc { |name, value| eval "defined? #{name} ? nil : #{name} = #{value}" } default.call :a, 43 default.call :b, 43 puts a puts b -------------- 42 def_proc.rb:9: undefined local variable or method `b' for main:Object (NameError) What is happening here? Well we cannot make b spring into live *outside* the proc scope. This all just to ask two questions Why using local variables and not instance variables? look at snippet (1) below Is the name ||= value syntax not good enough? I know it will overwrite nil and false values but more often than not it is quite good enough. If you really need what you want you will need some help from meta programming gurus. If I am not mistaken this can be done with things like binding_from_caller as can be found in Facets, also have a look at Maurico Fernandez' site http://eigenclass.org/ HTH. Robert (1) # vim: sts=2 sw=2 nu expandtab nowrap: @a = 42 def default name, value return if instance_variables.include? name # There even is instance_variable_exists? in # 1.8.6 instance_variable_set name, value end default "@a", 43 default "@b", 43 puts @a puts @b -------------- 42 43 -- We have not succeeded in answering all of our questions. In fact, in some ways, we are more confused than ever. But we feel we are confused on a higher level and about more important things. -Anonymous