Reputation: 55
I have some serious troubles to understand blocks with arguments. I would like to use such kind of Ruby code:
FooBar.foo do |foo_arg|
bar do |bar_arg|
define_method :hello!, foo_arg, bar_arg do
"Hello, #{foo_arg} and #{bar_arg}!"
end
end
end
include FooBar
hello!(:Alice, :Bob) # => "Hello, Alice and Bob!"
And to do so, I added thoses lines:
module FooBar
def self.foo &foo_block
instance_eval &foo_block
end
def self.bar &bar_block
instance_eval &bar_block
end
end
But because arguments between pipes are specials, I've got a syntax error. Thanks for any help!
Upvotes: 0
Views: 1792
Reputation: 4982
Your module seems to work correctly. The issue is your usage of define_method
. The parameters foo_arg
, and bar_arg
need to be part of the block passed to define_method
.
module FooBar
def self.foo(&foo_block)
instance_eval &foo_block
end
def self.bar(&bar_block)
instance_eval &bar_block
end
foo do |foo_arg|
bar do |bar_arg|
define_method :hello! do |foo_arg, bar_arg|
"Hello, #{foo_arg} and #{bar_arg}!"
end
end
end
end
include FooBar
hello!(:Alice, :Bob) # => "Hello, Alice and Bob!"
should do what you want.
Upvotes: 3