Ruby Proc:从类 B 中调用类 A 的方法,并使用类 B 的“方法”;
我不确定这是否真的可能,但我无法在任何地方找到明确的答案。此外,我发现很难仅用“搜索术语”来定义我的问题。所以我很抱歉,如果这个问题已经在其他地方得到了回答,我找不到它。
我想知道的是是否可以创建一个 Proc,其中包含未在定义 Proc 的位置中定义的方法。然后我想将该实例放入另一个具有该方法的类中,并使用提供的参数运行该实例。
这是我想要完成但不知道如何完成的示例。
class MyClassA
# This class does not have the #run method
# but I want Class B to run the #run method that
# I invoke from within the Proc within this initializer
def initialize
Proc.new { run 'something great' }
end
end
class MyClassB
def initialize(my_class_a_object)
my_class_a_object.call
end
# This is the #run method I want to invoke
def run(message)
puts message
end
end
# This is what I execute
my_class_a_object = MyClassA.new
MyClassB.new(my_class_a_object)
产生以下错误
NoMethodError: undefined method for #<MyClassA:0x10017d878>
我想我明白为什么,这是因为它试图调用 MyClassA
实例上的 run
方法而不是 MyClassB 中的方法
。但是,有没有办法让 run
命令调用 MyClassB
的 run
实例方法?
I am not sure whether this is actually possible, but I wasn't able to find a clear answer anywhere. Also I find it hard to define my question in mere 'search terms'. So I am sorry if this has already been answered somewhere else, I could not find it.
What I would like to know is if it is possible to create a Proc that holds a method that isn't defined in the location where the Proc is being defined. Then I would like to put that instance inside another class that does have the method, and run THAT one with the provided arguments.
Here is a sample of what I want to accomplish, but don't know how.
class MyClassA
# This class does not have the #run method
# but I want Class B to run the #run method that
# I invoke from within the Proc within this initializer
def initialize
Proc.new { run 'something great' }
end
end
class MyClassB
def initialize(my_class_a_object)
my_class_a_object.call
end
# This is the #run method I want to invoke
def run(message)
puts message
end
end
# This is what I execute
my_class_a_object = MyClassA.new
MyClassB.new(my_class_a_object)
The following error is produced
NoMethodError: undefined method for #<MyClassA:0x10017d878>
And I think I understand why, it is because it is trying to invoke the run
method on the MyClassA
instance rather than the one in MyClassB
. However, is there a way I could make the run
command invoke MyClassB
's run
instance method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码有两个问题:
MyClassA.new
不返回initialize
的值,它始终返回MyClassA
的实例。你不能只调用过程,你必须使用
instance_eval
方法在MyClassB
的上下文中运行它这是您的代码,已更正为您想要的工作方式:
There are two problems with your code:
MyClassA.new
does not return the value ofinitialize
it ALWAYS returns an instance ofMyClassA
.You cannot just call the proc, you have to use the
instance_eval
method to run it in the context ofMyClassB
Here is your code corrected to work as you want: