【问题标题】:Meta Programming in railsRails 中的元编程
【发布时间】:2020-01-22 13:15:22
【问题描述】:

我有一个名为 Person 的类,方法正在添加到名称、描述、昵称中 但是这些实例方法确实有相同的代码集

class Product
  def name
    p "this is the name of the product"
  end

  def description
    p "this is the descriptions of the product"
  end

  def nick_name
    p "this si the description of the nick name"
  end
end

class Person < Product
  %w(name description nick_name).map{|attr| attr.to_sym}.each do |definable_method|
    define_method definable_method do
      print "this is the #{definable_method} in the person"
      super
    end
  end  
end
 p1 = Person.new
 p1.name

预期结果

 this is the name in the person
 this is the name of product
p1.description

预期结果

  this is description in the person
  this is the descriptions of product

【问题讨论】:

    标签: ruby-2.0


    【解决方案1】:

    试试这个代码

    class Product
      def name
        p "this is the name of the product"
      end
    
      def description
        p "this is the descriptions of the product"
      end
    
      def nick_name
        p "this si the description of the nick name"
      end
    end
    
    class Person < Product
      %w(name description nick_name).map{|attr| attr.to_sym}.each do |definable_method|
        define_method definable_method do
          print "this is the #{definable_method} in the person\n"
          super()
        end
      end
    end
    
    p1 = Person.new
    p1.name
    
    

    【讨论】:

      猜你喜欢
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多