I don't think anybody has mentioned String#replace yet. Given the 
original code:

> wml_needed = [@question, @answer_explanation]
> wml_needed.each {|chunk| chunk = wml(chunk)}

and assuming that @question and @answer_explanation refer to String 
objects, then it can be made to work as follows:

  wml_needed.each {|chunk| chunk.replace(wml(chunk)) }

Quick explanation:

* @question contains a reference (pointer) to a string, let's call it 
str1
* @answer_explanation contains a reference to another string, str2
* wml_needed is a reference to an newly-created array which also 
contains references to str1 and str2
* using <ref>.replace, str1 and str2 are modified *in place*. All the 
existing references still point to the original strings, but those 
strings have mutated.
* since @q/@a and wml_needed both point to the same places, str1 and 
str2, both "see" the updated versions of str1 and str2

However I find this is rarely needed - and note that it doesn't work for 
objects which cannot be mutated (e.g. numbers).

If you need to modify instance variables, and there are only two, then 
using the KISS principle you can just write

  @question = wml(@question)
  @answer = wml(@answer)

Here, wml() presumably returns a new string in each case, and so 
@question and @answer are updated to point to the new string; the old 
ones will be garbage-collected at some point in the future, as long as 
there are no other live references to them.

If that's what you're actually trying to do, but you want to apply the 
DRY principle, then it *is* possible to read and write instance 
variables in a loop:

  [:@question, :@answer].each do |iv|
    instance_variable_set(iv, wml(instance_variable_get(iv)))
  end

Or, if you class has accessor methods (question, question=, answer and 
answer=) you can do

  ["question", "answer"].each do |iv|
    send("#{iv}=", wml(send(iv)))
  end

The latter example in particular is worth working through until you 
understand how it works.

Of course, if your data naturally sits in an array, then you could just 
keep a single instance variable which refers to the array, and don't 
keep duplicate instance variables. Then you can just use map or map! to 
update the array.

HTH,

Brian.
-- 
Posted via http://www.ruby-forum.com/.