James Gray
12/7/2006 2:22:00 PM
On Dec 7, 2006, at 1:25 AM, Gary Boone wrote:
>
> Suppose you want to do several runs of a program or function, varying
> the parameters each time. You start with a hash of parameter lists:
>
> params = { speed=>[1,2,3], beta=>[0.1, 0.002, 0.4], x=>['a',
> 'b'] }
>
> Given this set, you'll call the test function 18 times:
>
> test_function( {speed=>1, beta=>0.1, x=>'a'} )
> test_function( {speed=>1, beta=>0.1, x=>'b'} )
> test_function( {speed=>1, beta=>0.002, x=>'a'} )
> ... etc
See if this gives you some ideas:
#!/usr/bin/env ruby -w
def call_with(meth, params, selected = Hash.new)
params = params.dup
key = params.keys.sort_by { |k| k.to_s }.first
choices = params.delete(key)
choices.each do |choice|
selected = selected.merge(key => choice)
if params.empty?
send(meth, selected)
else
call_with(meth, params, selected)
end
end
end
def print_args(args)
p args
end
call_with :print_args, :speed => [1, 2, 3],
:beta => [0.1, 0.002, 0.4],
:x => ["a", "b"]
# >> {:speed=>1, :beta=>0.1, :x=>"a"}
# >> {:speed=>1, :beta=>0.1, :x=>"b"}
# >> {:speed=>2, :beta=>0.1, :x=>"a"}
# >> {:speed=>2, :beta=>0.1, :x=>"b"}
# >> {:speed=>3, :beta=>0.1, :x=>"a"}
# >> {:speed=>3, :beta=>0.1, :x=>"b"}
# >> {:speed=>1, :beta=>0.002, :x=>"a"}
# >> {:speed=>1, :beta=>0.002, :x=>"b"}
# >> {:speed=>2, :beta=>0.002, :x=>"a"}
# >> {:speed=>2, :beta=>0.002, :x=>"b"}
# >> {:speed=>3, :beta=>0.002, :x=>"a"}
# >> {:speed=>3, :beta=>0.002, :x=>"b"}
# >> {:speed=>1, :beta=>0.4, :x=>"a"}
# >> {:speed=>1, :beta=>0.4, :x=>"b"}
# >> {:speed=>2, :beta=>0.4, :x=>"a"}
# >> {:speed=>2, :beta=>0.4, :x=>"b"}
# >> {:speed=>3, :beta=>0.4, :x=>"a"}
# >> {:speed=>3, :beta=>0.4, :x=>"b"}
James Edward Gray II