Hello, what is the scope of a variable created inside an eval()
statement? To demonstrate what I mean, I created the following program:
a=1
puts local_variables.sort.collect{|v|"1 #{v}: #{eval(v)}"}
eval("b=2")
puts local_variables.sort.collect{|v|"2 #{v}: #{eval(v)}"}
c=eval("b")
d=b
puts local_variables.sort.collect{|v|"3 #{v}: #{eval(v)}"}
This gives as output:
1 a: 1
1 c:
1 d:
2 a: 1
2 b: 2
2 c:
2 d:
tmp.rb:6: undefined local variable or method `b' for main:Object
(NameError)
Apparently, Ruby creates immediately the variables a,c,d (so all the
variables that are on the left-hand-side of an assignment), even before
he actually processed the assignment.
After processing the line "eval("b=2")", Ruby also created the local
variable b, which is accessible via eval("b"), but not directly (Ruby
crashes on line 6, "d=b" because he does not know local variable b,
which is clearly NOT the case, since he did write out local variable b
correctly).
Any idea how these things work in Ruby and why my above program does
not?
If you are wondering why I need this: I want to develop a
"named-argument" system for ruby-methods. My plan is to pass in a hash
all the optional arguments and automatically create variables for all
the keys in this hash. This generic procedure to create variables from
the hash-keys, does not know the names for these variables, but the rest
of the method that uses the named arguments does:
def
some_method(required_arg1,required_arg2,opt_arg_hash={:opt_arg1=>nil,:op
t_arg2=>nil})
#this generic method should create the variables opt_arg1 and opt_arg2
process_opt_args(opt_arg_hash)
#here we should be able to use the variables opt_arg1 and opt_arg2
directly, without having
#to write opt_arg_hash[:opt_arg1] and opt_arg_hash[:opt_arg2]
puts(opt_arg1)
puts(opt_arg2)
end
Greetings,
Geert.