簡體   English   中英

Ruby class_eval和yield

[英]Ruby class_eval and yield

伙計,我今天要去皮洋蔥層,反正這是代碼

class MyClass
  def initialize(dynamic_methods)
    @arr = Array.new(dynamic_methods)
    @arr.each { |m|
      self.class.class_eval do
        define_method(m) do
          "<#{yield self if block_given?}>" 
        end
      end
    }
    end
end

tmp = MyClass.new ['method1', 'method2', 'method3']
tmp.method1 do |t|
  "here"
end

我的問題是我正在嘗試在執行方法時而不是在創建方法時訪問define_method(m)中的“ here”。 當前的語句“ <#{如果block_given會屈服於自己?}>”不會給我那句話。 如果您想知道,我必須保留這部分代碼,但是我可以對MyClass進行所有更改。

tmp = MyClass.new ['method1', 'method2', 'method3']
tmp.method1 do |t|
  "here"
end

任何人都可以幫助語法嗎? 在此先感謝您的幫助。

更新:請參閱下面的我的答案。

嘗試更換

define_method(m) do
  "<#{yield self if block_given?}>" 
end

與:

define_method(m) do |&block|
  "<#{block.call if block}>" 
end

這應該適用於1.8.7及更高版本。 您也可以嘗試使用module_eval

self.class.module_eval %Q{
  def #{m}(&block)
    "<\#{block.call if block}>"
  end
}

在Sergei的大量反饋和我自己的幫助下,我設法使其正常運行

class MyClass
  def initialize(dynamic_methods)
    @arr = Array.new(dynamic_methods)
    @arr.each { |m|
      self.class.module_eval %Q{
        def #{m}(&block)
          yield(self) if block_given?
        end
      end
    }
    end
end

tmp = MyClass.new ['method1', 'method2', 'method3']
tmp.method1 do |t|
  "here"
end

如您所知,Sergei的建議有一些細微的調整,因此感謝您對Sergei的所有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM