0
塊在Ruby中,我可以說:類在Python
def get_connection
db = connect_to_db()
yield
db.close()
end
然後調用它
get_connection do
# action1.....
# action2.....
# action3.....
end
在Python,我不得不說
def get_connection(code_block):
db = connect_to_db()
code_block()
db.close()
get_connection(method1)
def method1():
# action1.....
# action2.....
# action3.....
這並不方便,因爲我必須創建一個額外的method1
。請注意,method1
可能很大。有沒有什麼辦法模仿Python中的Ruby匿名塊?
我可以擺脫創建班級嗎? – 2013-05-02 05:11:28
@AlanDert見我編輯 – 2013-05-02 05:17:21
爲什麼不使用本地方法? – 2013-05-02 05:24:27