2007/12/7, Vasyl S. [email protected]:
I wonder if there is any way to create local variables dynamically,
for example, given
def foo
bar
puts x, y
end
is it possible for bar to somehow create and initialize x and y?
Binding doesn’t seem to be modifiable…
You cannot do this easily because of the method / variable ambiguity.
There’s a hack to do it: you need to define them before you use them
but it is ugly and does not work properly.
14:23:17 ~
$ ruby <<XXX
def foo
x=y=nil
bar(binding)
puts x,y
end
def bar(b)
eval(“x=1;y=2”,b)
end
foo
XXX
1
2
The problem with dynamically introducing local variables is that your
code needs to be statically aware of them in order to use them. Even
though you can inject any number of additional local variables into a
binding, they won’t get used because they do not appear in the code of
that method.
A much better solution to the problem of storing dynamic values is a
Hash.
def foo
data = {}
bar data
puts data[:x], data[:y]
end
def bar(x)
x[:x] = 1
x[:y] = 2
end
But you can as well return multiple values
def foo
x,y = bar
puts x, y
end
def bar
return 1,2
end
Kind regards
robert