我想知道如何在另一个类的类实例中调用方法.
这就是我提出的
class ClassA def method return "This is a method_from_class_A" end end class ClassB def initialize @method_from_class_A=instance.method end def method_calls_method @method_from_class_A end end instance=ClassA.new instance2=ClassB.new puts instance2.method_calls_method
但我得到这个错误:
Testing.rb:9:in
initialize': undefined local variable or method
instance’ for # (NameError) from
Testing.rb:19:innew' from Testing.rb:19:in
‘
我该怎么办呢?
感谢您的答复.
解决方法
根据你的描述,这似乎是你想要的:
class ClassB def initialize @instance_of_class_a = ClassA.new end def method_calls_method @instance_of_class_a.method end end
或者传入ClassA实例(这称为依赖注入):
class ClassB def initialize(class_a_instance) @instance_of_class_a = class_a_instance end def method_calls_method @instance_of_class_a.method end end instance_a = ClassA.new instance_b = ClassB.new(instance_a) puts instance_b.method_calls_method