From: Xiong Chiamiov Date: 2008-09-12T06:12:56+09:00 Subject: Re: pass by reference in each loop Pedro Silva wrote: > Ruby doesn't pass arguments by reference it passes them by value. What > is passed to functions/blocks is the reference value. Although that sounds exactly like passing by reference (doesn't it?), I've come to understand today the nuance of how Ruby acts differently (at least, I think). In, say, C (ugh!), if I have some variable x and pass it to a function by reference, it modifies the original x. If I pass by copy instead, it copies it and modifies the copy, but not the original. Ruby, however, (correct me if I'm wrong!) passes (essentially) by reference. However, the difference is in how it treats the value passed. When you modify it, instead of modifying the object that the reference points to, you modify the reference itself to point to something else. This brings me back to my original question. While map! looked exactly right, it modifies where the references in the array point to, rather than modifying the values they pointed to, which means that my original variables are not modified. Robert Klemme wrote: >@question, @answer_explanation = > [@question, @answer_explanation].map {|x| f(x)} which *does* work, as it assigns the values back to the variables, but it defeats the purpose of the thing. Perhaps I should explain a little bit better why I'm going about this: I'm building a lightweight parsing language. The function wml() parses this. I have a lot of user input, some of which I want to parse, but some I don't. So then, I wanted to avoid writing: @a = wml(@a) @b = wml(@b) @c = wml(@c) ... because the list could potentially be quite long, and I'm the good kind of lazy (the one referred to in the Camel book). Robert's solution would allow me to only write the function name once, but the variables I'd still have to type twice, and I really like DRY. My first thought was to store a list of all those variables in an array and loop through them, as it's then very easy to add an additional variable. Perhaps I'm approaching this the complete wrong way, though? -- Posted via http://www.ruby-forum.com/.