From: Joel VanderWerf Date: 2008-01-03T04:21:13+09:00 Subject: Re: Dynamically add a method to a TestCase Achim Domma wrote: > Hi, > > I'm experimenting with the dynamic features of ruby to add methods to > a TestCase. Here is my test script: > > require 'watir' > require 'test/unit' > > class MyTest < Test::Unit::TestCase > end > > for num in ["a","b","c"] > MyTest.send(:define_method,"test_" + num) { > assert(false,"->"+num) > } > end > > It works fine so far, but all asserts display "->c" as error message. > I don't understand why! Any hint? How to fix it? It's the way the 'for' construct scopes the 'num' variable. All three method definition blocks are seeing 'num' in the same scope, so they all get the last assigned value, "c". Try this: procs = [] for num in ["a","b","c"] #["a","b","c"].each do |num| procs << proc { num } end procs.each do |pr| puts pr.call end That prints three 'c's. Now uncomment the 'each' line and comment out the 'for' line, and you'll see the scope difference! -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407