【问题标题】:Difference between passing arguments to define_method and to the following block?将参数传递给 define_method 和以下块之间的区别?
【发布时间】:2013-08-12 11:07:58
【问题描述】:

我对@9​​87654321@的以下代码感到困惑:

# The guts of life force within Dwemthy's Array
class Creature

  # Get a metaclass for this class
  def self.metaclass; class << self; self; end; end

  # Advanced metaprogramming code for nice, clean traits
  def self.traits( *arr )
    return @traits if arr.empty?

    # 1. Set up accessors for each variable
    attr_accessor( *arr )

    # 2. Add a new class method to for each trait.
    arr.each do |a|
      metaclass.instance_eval do
        define_method( a ) do |val|
          @traits ||= {}
          @traits[a] = val
        end
      end
    end

    # 3. For each monster, the `initialize' method
    #    should use the default number for each trait.
    class_eval do
      define_method( :initialize ) do
        self.class.traits.each do |k,v|
          instance_variable_set("@#{k}", v)
        end
      end
    end

  end

  # Creature attributes are read-only
  traits :life, :strength, :charisma, :weapon
end

以上代码用于新建类,如下:

class Dragon < Creature
  life( 1340 )     # tough scales
  strength( 451 )  # bristling veins
  charisma( 1020 ) # toothy smile
  weapon( 939 )    # fire breath
end

我需要更多地自学元编程的基础知识,但现在我只想知道,val 块参数从哪里来的 define_method( a ) do |val|?它表示分配给每个特征的点值,但我不明白这些数字中的每一个如何成为一个块参数。

另外,为什么a 在括号中传递给define_method,而val 作为块参数传入?

我已阅读 this question 关于 define_method 参数的主题,但它没有解决将参数传递给 define_method 而不是块的原因。

【问题讨论】:

    标签: ruby metaprogramming


    【解决方案1】:

    在表格中

    define_method(:foo){|x| ...}
    

    :foo 是方法名,x 是参数。他们有不同的角色。同理:

    def foo(x)
      ...
    end
    

    【讨论】:

    • 好的。我明白了。 define_method 怎么知道 val 是什么?例如,为什么它不认为1340 是另一个trait,而不是像它那样将其分配给val
    • Nvm。我想了更多,我想我现在明白了。非常感谢。
    • val 是一个变量名。它是什么并不重要。就像def foo(x); puts x end def foo(y); puts y end 相同,define_method(:foo){|x| puts x}define_method(:foo){|y| puts y} 相同。
    • 知道了。我是在一个太特殊的背景下思考的。
    猜你喜欢
    • 1970-01-01
    • 2016-02-24
    • 2010-09-10
    • 2016-03-07
    • 2013-03-28
    • 2014-02-06
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多