【发布时间】:2013-08-12 11:07:58
【问题描述】:
我对@987654321@的以下代码感到困惑:
# 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