我更新了这个问题,以更好地反映我需要掌握的问题。下面的例子有点工作,但是我如何访问 Sub 类,然后我在 Base 类中定义了它?在课外打电话不是更好吗?如果是这样,我该怎么做?在这个例子中我遇到的第二个问题是如何获取值以便我可以在另一个类中使用它们。在这里,我将值存储在一个数组中,稍后我需要在另一个类中解包。我应该不能为此使用 proc 吗?
基本上我想要做的是根据它们是否嵌套将方法分类为两个不同的类。
class Sub
def initialize(base_class_method)
@base_class_method = base_class_method
@sub_methods = []
end
# omitted code here
def base_class_method
@base_class_method
end
def sub_actions(method)
@sub_methods << method
end
def return_sub_methods
@sub_methods
end
def method_missing(sub_method, &block)
if sub_method
sub_method
else
super
end
end
end
class Base
def initialize
@base_methods = []
end
# omitted code here
def base_actions(method)
@base_methods << method
end
def return_base_methods
@base_methods
end
def method_missing(method, &block)
if block_given?
Sub.new(method).instance_eval(&block)
elsif method
base_actions(method)
else
super
end
end
end
base = Base.new
base.instance_eval do
something1
something_with_a_block do
something_inside_block1_1
something_inside_block1_2
end
something2
something_with_a_block2_2 do
something_inside_block2_1
end
end
p base.return_base_methods #=> [:something1, :something2] works!