2017-07-26 31 views
2

我想引用與它一起傳遞的塊內的一個對象的參數之一。如何在傳入塊中引用對象的參數?

def command(attributes = {}, &block) 
    yield 
end 

command(attr_1: 'Open Mike Night', 
    attr_2: 2033392, 
    attr_3: [9.29, 10.08, 12.32]) do |event| 

    event.message.delete 

    puts "#{self.attributes[:attr_1]}" # <-- That didn't work. 

end 

是這樣的可能性,如果是這樣的話,我該怎麼做呢?我應該看什麼?

+0

最後一個鍵應該是attr_3嗎? –

+0

@ sagarpandya82你是對的,對不起! – Calculon

+0

你的'command'定義中有'yield'嗎? –

回答

0

關閉我的頭頂,你可以做這樣的事情。警告我不知道這是否適合生產代碼。

此代碼通過遍歷參數散列的鍵來爲每個鍵創建實例變量。

def command(attributes = {}, &block) 
    attributes.each_key { |key| 
    instance_variable_set("@#{key}",attributes[key]) 
    } 
    yield 
end 

command(attr_1: 'Open Mike Night', 
     attr_2: 2033392, 
     attr_3: [9.29, 10.08, 12.32]) do |event| 

    puts "#{@attr_1}" 
end 

打印::

Open Mike Night 
+0

如果方法在與調用它不同的範圍內定義,則這不起作用。該塊的範圍由它的周圍環境決定,所以如果在A類中定義了'command'但是在B類中調用了方法,那麼'@ attr_1'將在'B'的上下文中進行評估,而不是'A' –

0

他們屈服的塊:)

def command(attributes = {}) 
    yield self, attributes 
end 

attributes = { attr_1: 'Open Mike Night', attr_2: 2033392, attr_3: [9.29, 10.08, 12.32] } 

command(attributes) do |obj, attrs| 
    p "#{obj.object_id}, #{attrs[:attr_1]}" 
end 
# => "70309890142840, Open Mike Night" 

然後當我們調用command,我們可以在塊使用相應instance_variable引用每個鍵的值在方法範圍內可用的任何方法,常量或變量都可以作爲參數yield作爲塊變量發送到塊中。然後你可以隨心所欲地做任何事情。在這種情況下,attrs也是一個完全可選的變量,並且該塊在沒有它的情況下將是有效的。

command(attributes) { |obj| p obj.object_id } # => 70309890142840 

P.S.如果您使用的是yield,則方法簽名中不需要&block。你也沒有在你的問題中給yield一個參數,而是將一個|event|變量傳遞給該塊,該塊將會是nil。所以我只是在上面的例子中把它留了下來。

相關問題