Lon*_*ler 5 ruby metaprogramming class object
以下是Ruby第6章"为什么的尖锐指南"中的Ruby代码片段,他试图在Ruby中演示元编程:
# Get a metaclass for this class
def self.metaclass; class << self; self; end; end
Run Code Online (Sandbox Code Playgroud)
我对Ruby并不熟悉,但这是扩展形式的样子吗?
def self.metaclass
def self.self
end
end
Run Code Online (Sandbox Code Playgroud)
至少这是我理解它的方式.但是,它仍然无法理解这段代码的作用.它的目的是什么?
在代码中,为什么添加这个:
arr.each do |a|
metaclass.instance_eval do
define_method( a ) do |val|
@traits ||= {}
@traits[a] = val
end
end
end
Run Code Online (Sandbox Code Playgroud)
如果我理解正确,这段代码会给@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
Run Code Online (Sandbox Code Playgroud)
在使用中:
class Dragon < Creature
life( 1340 ) # tough scales
strength( 451 ) # bristling veins
charisma( 1020 ) # toothy smile
weapon( 939 ) # fire breath
end
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
简而言之:您所看到的定义了一个metaclass
在Creature
类本身上命名的方法(而不是实例).当您运行此方法时,它会找到metaclass Creature
并返回该方法.
在'网络周围阅读一个对象的"元类".
归档时间: |
|
查看次数: |
1647 次 |
最近记录: |