2013-10-14 81 views
1

傳入塊我想塊傳遞給一個函數,然後調用該塊與一些額外的參數如下:參數傳遞給Ruby中

def foo(&block) 
    some_array = (1..3).to_a 
    x = 7 # Simplified 
    result = some_array.map &block # Need some way to pass in 'x' here 
end 

def a_usage_that_works 
    foo do |value| 
    value 
    end 
end 

def a_usage_that_doesnt_work 
    foo do |value, x| 
    x # How do I pass in x? 
    end 
end 

# rspec to demonstrate problem/required result 
describe "spike" do 
    it "works" do 
    a_usage_that_works.should == [1,2,3] 
    end 
    it "doesn't work" do 
    a_usage_that_doesnt_work.should == [7, 7, 7] 
    end 
end 

如何傳遞的附加參數塊?

回答

2

創建另一個塊並從中調用第一個塊。

def foo(&block) 
    some_array = (1..3).to_a 
    x = 7 # Simplified 
    result = some_array.map {|elem| block.call(elem, x)} 
end 
1

您傳遞給它的塊。

def foo(&block) 
    some_array = [1,2,3] 
    x = 7 
    some_array.map{|el| yield el, x} 
end 

p foo{|p1, p2| p2} #=>[7,7,7] 
p foo{|p1, p2| p1} #=>[1,2,3] 
+0

這不通過所提供的測試。它拋棄了'some_array'的值。 – Stefan

+0

@Stefan(Code editted)這是你想要的嗎? – steenslag

+0

是的,就是這樣。 – Stefan

0

可以使用higher-order function生成一個簡化的功能:

讓我們假設我們通過foo塊將接受value, x

天真策略,使用內聯定義x

def foo(&block) 
    some_array = (1..3).to_a 
    x = 7 
    simple_func = proc {|value| block.call(value, x) } 
    result = some_array.map &simple_func 
end 

策略使用分離的擔憂:

def get_simple_func(block) 
    # This assumes x won't change per iteration. 
    # If it can change, you can move the calculation inside the proc. 
    # Moving it inside also allows the calculation to depend on "value", in case you want that. 
    x = complex_calculation_for_x() 
    proc {|value| block.call(value, x) } 
end 

def foo(&block) 
    some_array = (1..3).to_a 
    simple_func = get_simple_func(block) 
    result = some_array.map &simple_func 
end 

顯然,你不應該使用這個時候x是一個文字值,因爲它會過度工程。但是隨着x的計算變得更加複雜,將其分離出來使代碼更具可讀性。此外,foo可以專注於將函數應用於some_array的具體任務。