From: grady@... (Steven Grady) Date: 2000-11-30T08:10:01+09:00 Subject: [ruby-talk:6653] each/for binding confusion and resolution As I am still learning the language, I am hitting things which are confusing. I thought I'd share one with people here -- perhaps it may spark some conversation as to whether it violates POLS. In essence, one problem I had came down to the following: procs = [] for v in [1, 2] procs << proc { v } end procs.collect { |p| p.call } -> [2, 2] I was hoping for [1, 2]. It took me a little while to realize that the reason this would happen is that the proc uses the variable "v" rather than the object to which it is bound, and since the binding stays the same through the loop, the two procs return exactly the same value. Since I wanted to have each proc return something different, I thought the right solution would be to somehow create a proc (or method, or closure, or lambda, or whatever) that interpolated the _value of "v"_ rather than "v" itself. After some exploration (and reading a bit of the book), I discovered that an alternate solution is: procs = [] [1, 2].each { |v| procs << proc { v } } procs.collect { |p| p.call } -> [1, 2] By using rather than , I could have v be local to the loop, and therefore (?) get a different binding inside each proc. So now I understand enough to get my original code to work. I am left with a few questions: Is my analysis correct? Does create a new binding every time through the loop? Is this the right way to fix the problem? It apparently imposes some overhead in that there is a binding stored with each proc, and a binding resolution occurs each time the proc is called. I think I'd be happier to have a way of specifying that I want the _value_ of "v", analogous to the #{} notation in double-quoted strings. Is there a straightforward way to fix the code that uses a loop, rather than an iterator? I don't need it, but it would be interesting to know of alternate solutions. Ruby kicks ass. Thanks for any help. -- Steven "I wish _I_ was a tiger." "A common lament."