以下是来自 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
至少我是这么理解的。但是,它仍然不完全理解这段代码的作用。 它的目的是什么?
进一步在代码中,为什么添加这个:
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
最佳答案
class Foo
def self.bar # Create a method invoked by Foo.bar instead of Foo.new.bar
42 # the return value of this method (value of last expression)
end
end
class Foo
def self.jim # Another method on the class itself
class << self # Change the 'self' to be the metaclass of the current object
self # Evaluate the current 'self' as the 'return value' of
end # class<<self…end; and since this is the last expression in
end # the method, its value is the return value for the method
end
简而言之:您所看到的在 Creature
类本身(不是实例)上定义了一个名为 metaclass
的方法。当您运行此方法时,它会找到 Creature
的元类并返回它。
Read around the 'net对象的“元类”是什么。
关于ruby - 这段 Ruby 代码的作用是什么? : def self. 元类;类<< self ;自己;结尾;结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10099157/