我試圖動態定義,通過另一個函數,它接受一個選項參數調用函數:是否可以在Ruby中使用可選參數定義一個塊?
class MyClass
["hour", "minute", "second"].each do |interval|
define_method "get_#{interval}" do |args|
some_helper(interval, args)
end
end
def some_helper(interval, options={})
# Do something, with arguments
end
end
我希望能夠調用這兩個方面對MyClass的不同方法(與和無可選參數):
mc = MyClass.new
mc.get_minute(:first_option => "foo", :second_option => "bar")
mc.get_minute # This fails with: warning: multiple values for a block parameter (0 for 1)
在第二呼叫,以分鐘,我看到這樣的警告:
警告:多個值塊參數(0 1)
- 是否有寫爲「*的get_」方法塊,使此警告不會拿出一個辦法?
- 我在濫用define_method嗎?
感謝您指出了這一點! – Readonly 2009-01-16 21:30:23