按照要求,這裏是一個例子,我的意思是將選擇與產量鏈接在一起。裸露的骨頭實現可能是這個樣子:
def choose_one_of_each(choices,results,&block)
if choices.empty?
yield results
else
c = choices.dup
var,val = c.shift
choose(val) { |v|
choose_one_of_each(c,results.update(var => v),&block)
}
end
end
def choose(options,&block)
case options
when Hash then choose_one_of_each options,{},&block
when Range then options.each { |item| yield item rescue nil }
else options.each { |item| yield item rescue nil }
end
end
而且你會使用這樣的(從你的例子有所擴大,說明如何使用部分進行交互):
a = 7
b = 'frog'
choose(
:one => [a,b],
:two => ['stay','go','punt'],
:three => {:how => ['in the car','in a boat','by magic'],:how_fast => 0..2 }
) do |choices|
raise "illegal" if choices[:one] == a
raise "You can't stay fast!" if choices[:two] == 'stay' and choices[:three][:how_fast] > 0
raise "You go that slow!" if choices[:two] == 'go' and choices[:three][:how_fast] < 1
print choices.inspect,"\n"
end
將產生這樣的事情(因爲打印):
{:three=>{:how=>"in the car", :how_fast=>0}, :one=>"frog", :two=>"stay"}
{:three=>{:how=>"in the car", :how_fast=>0}, :one=>"frog", :two=>"punt"}
{:three=>{:how=>"in the car", :how_fast=>1}, :one=>"frog", :two=>"go"}
{:three=>{:how=>"in the car", :how_fast=>1}, :one=>"frog", :two=>"punt"}
{:three=>{:how=>"in the car", :how_fast=>2}, :one=>"frog", :two=>"go"}
{:three=>{:how=>"in the car", :how_fast=>2}, :one=>"frog", :two=>"punt"}
{:three=>{:how=>"in a boat", :how_fast=>0}, :one=>"frog", :two=>"stay"}
{:three=>{:how=>"in a boat", :how_fast=>0}, :one=>"frog", :two=>"punt"}
{:three=>{:how=>"in a boat", :how_fast=>1}, :one=>"frog", :two=>"go"}
{:three=>{:how=>"in a boat", :how_fast=>1}, :one=>"frog", :two=>"punt"}
{:three=>{:how=>"in a boat", :how_fast=>2}, :one=>"frog", :two=>"go"}
{:three=>{:how=>"in a boat", :how_fast=>2}, :one=>"frog", :two=>"punt"}
{:three=>{:how=>"by magic", :how_fast=>0}, :one=>"frog", :two=>"stay"}
{:three=>{:how=>"by magic", :how_fast=>0}, :one=>"frog", :two=>"punt"}
{:three=>{:how=>"by magic", :how_fast=>1}, :one=>"frog", :two=>"go"}
{:three=>{:how=>"by magic", :how_fast=>1}, :one=>"frog", :two=>"punt"}
{:three=>{:how=>"by magic", :how_fast=>2}, :one=>"frog", :two=>"go"}
{:three=>{:how=>"by magic", :how_fast=>2}, :one=>"frog", :two=>"punt"}
我可以自己找出延續,如果我必須,我只是真的希望有一個更便攜的解決方案。 – 2009-02-27 02:47:35
+1 - Amb類似乎已經實現了您尋找的解決方案。我沒有看到callcc被棄用的跡象 - http://ruby-doc.org/core-1.9/classes/Continuation.html – rampion 2009-02-27 02:56:32
嗯...我必須擊中一篇過時的文章。它似乎在某些實現上不受支持,但可能不是交易斷路器。 – 2009-02-27 03:36:12