I’m trying to dynamically define functions that call through to another function that takes an options parameter:
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
I’d like to be able to call the different methods on MyClass in these two ways (with and without optional arguments):
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)
On the second call to minute, I see this warning:
warning: multiple values for a block parameter (0 for 1)
- Is there a way to write the block for the ‘get_*’ method so that this warning won’t come up?
- Am I abusing define_method?
The only change you need to make is to change
argsto*args. The*indicates thatargswill contain an array of optional arguments to the block.