【问题标题】:Ruby Proc: Invoking method from Class A from within Class B, and using Class B's 'method'Ruby Proc:从 B 类中从 A 类调用方法,并使用 B 类的“方法”
【发布时间】:2010-11-03 02:27:43
【问题描述】:

我不确定这是否真的可行,但我无法在任何地方找到明确的答案。此外,我发现很难仅用“搜索词”来定义我的问题。所以很抱歉,如果这个问题已经在其他地方得到了回答,我找不到它。

我想知道的是,是否可以创建一个 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 命令调用MyClassBrun 实例方法?

【问题讨论】:

    标签: ruby lambda proc-object


    【解决方案1】:

    你的代码有两个问题:

    1. MyClassA.new 不返回 initialize 的值,它总是返回 MyClassA 的实例。

    2. 你不能只调用proc,你必须使用instance_eval方法在MyClassB的上下文中运行它

    以下是您的代码已更正,可按您的需要工作:

    class MyClassA    
      def self.get_proc
        Proc.new { run 'something great' }
      end
    end
    
    class MyClassB
    
      def initialize(my_class_a_object)
       instance_eval(&my_class_a_object)
      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.get_proc
    MyClassB.new(my_class_a_object) #=> "something great"
    

    【讨论】:

    • 感谢 m8!是的,对不起,这是我试图做的一个坏例子。这实际上不是我遇到的实际问题,但是在这里添加一个有点复杂,所以我快速写了一个。使用初始化方法犯了错误,正如你所说,它当然会返回实例。感谢您的解决方案! :)
    猜你喜欢
    • 2013-06-12
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2022-06-11
    • 1970-01-01
    相关资源
    最近更新 更多