[英]Ruby method with optional options and &block parameter
嘿
是否可以將可選屬性和塊作為方法調用的參數?
示例:我必須打電話
method(foo, foo: bar, -> { do_something }
並嘗試了
def method(foo, *bar, &block) end
就我的理解而言,區塊始終必須位於最后位置?
經過一番研究,我發現一元(?) *
似乎適用於數組。 由於我嘗試傳遞Hash
將代碼更改為
def method(foo, bar={}, &block) end
但這也不能解決問題。 我猜是因為他不知道酒吧的終點和街區的起點。
有什么想法或建議嗎? 先感謝您
追加:只是出於好奇,為什么我需要這個。 我們運行着一個大的json模式,並有一個小的DSL,它可以根據模型定義來構建json。 在不贅述的情況下,我們想實現exportable_scopes。
class FooBar exportable_scope :some_scope, title: 'Some Scope', -> { rewhere archived: true } end
在某些初始化程序上,這應該發生:
def exportable_scope scope, attributes, &block scope scope block if attributes.any? attributes.each do |attribute| exportable_schema.scopes[scope] = attribute end else exportable_schema.scopes[scope] = {title: scope} end end
所以這工作正常,我只需要提示方法參數即可。
對的,這是可能的。
當混合不同種類的參數時,必須按特定順序將它們包含在方法定義中:
上面的順序有些靈活。 我們可以定義一個方法,並從一個splat參數開始,然后是幾個可選的位置參數,等等,開始參數列表。 即使Ruby允許這樣做,通常也是非常糟糕的做法,因為代碼將很難閱讀甚至難以調試。 通常最好使用以下順序:
例:
def meditate cushion, meditation="kinhin", *room_items, time: , posture: "kekkafuza", **periods, &b
puts "We are practicing #{meditation}, for #{time} minutes, in the #{posture} posture (ouch, my knees!)."
puts "Room items: #{room_items}"
puts "Periods: #{periods}"
b.call # Run the proc received through the &b parameter
end
meditate("zafu", "zazen", "zabuton", "incense", time: 40, period1: "morning", period2: "afternoon" ) { puts "Hello from inside the block" }
# Output:
We are practicing zazen, for 40 minutes, in the kekkafuza posture (ouch, my knees!).
Room items: ["zabuton", "incense"]
Periods: {:period1=>"morning", :period2=>"afternoon"}
Hello from inside the block
注意,調用該方法時,我們有:
請注意上面服務器的示例,只是為了說明混合不同類型參數的可能性。 在實際代碼中構建這樣的方法將是一種不好的做法。 如果一個方法需要那么多參數,最好將其拆分為較小的方法。 如果絕對有必要將那么多數據傳遞給單個方法,則我們可能應該創建一個類,以更有條理的方式存儲數據,然后將該類的實例作為單個參數傳遞給該方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.