On Dec 7, 3:28 pm, "Robert Klemme" <shortcut...@googlemail.com> wrote:
> 2007/12/7, Vasyl Smirnov <vasyl.smir...@gmail.com>:
> > 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.
Thanks for clarifying that.
> 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
The hash approach is nice, and I actually use it for some other code.
I've posted this question because I wanted to eliminate the need to
write "x, y = bar" and just go with "bar".
The reason is that I have a bunch of methods, each starting with a
kind of "x, y = bar", only with longer variable names.
So it looked like it would be nice to somehow reduce them.
So, it looks like I should either a) stop whining about it, or b) use
one of the proposed approaches.