【发布时间】:2010-11-09 16:07:46
【问题描述】:
我正在努力编写类似于下面示例的代码(但实际上做了一些有用的事情)。传递给def_my_method 的块当然是在类的上下文中创建的,当我想在具有实例方法的实例的上下文中对其进行评估时。我该怎么做?
module Formatters
# Really useful methods, included in several classes
def format_with_stars(str)
return "*** #{str} ***"
end
end
class Test
include Formatters
STRINGS = ["aa", "bb"]
def self.def_my_method(method_name, another_parameter, &format_proc)
define_method(method_name) do
# In reality, some more complex code here, then...
return STRINGS.map(&format_proc)
end
end
def_my_method(:star_strings, "another_parameter") { |str| format_with_stars(str) }
# Define other methods
end
tt = Test.new
puts tt.star_strings
# Throws undefined method `format_with_stars' for Test:Class (NoMethodError)
【问题讨论】:
标签: ruby metaprogramming