以下は、 Why's Poignant Guide to Ruby Chapter 6からの Ruby コード スニペットで、Rubyでのメタプログラミングのデモンストレーションを試みています。
# Get a metaclass for this class
def self.metaclass; class << self; self; end; end
私は Ruby に詳しくありませんが、これを拡張するとどうなるでしょうか。
def self.metaclass
def self.self
end
end
少なくとも私はそう理解しています。ただし、このコードが何をするのかはまだ正確には理解されていません。その目的は何ですか?
コードのさらに先に、Why がこれを追加します。
arr.each do |a|
metaclass.instance_eval do
define_method( a ) do |val|
@traits ||= {}
@traits[a] = val
end
end
end
私が正しく理解している場合、このコードは、指定された名前と値で @traits に新しい値を追加します。あれは正しいですか?
助けてくれてありがとう。見たい人のために、私に問題を引き起こした完全なソースコードを以下に示します。
# 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