Sau đây là một Ruby đoạn mã từ Why's Poignant Guide to Ruby Chapter 6, nơi ông cố gắng để chứng minh lập trình meta trong Ruby:Mã Ruby này làm gì ?: def self.metaclass; lớp << tự; tự; kết thúc; cuối
# Get a metaclass for this class
def self.metaclass; class << self; self; end; end
Tôi không phải là rất quen thuộc với Ruby, nhưng là này những gì nó sẽ như thế nào ở dạng mở rộng?
def self.metaclass
def self.self
end
end
Ít nhất đó là cách tôi hiểu điều đó. Tuy nhiên, nó vẫn không hiểu chính xác mã này là gì. Mục đích của nó là gì?
Tiếp tục trên trong các mã, Tại sao bổ sung này:
arr.each do |a|
metaclass.instance_eval do
define_method(a) do |val|
@traits ||= {}
@traits[a] = val
end
end
end
Nếu tôi hiểu nó một cách chính xác, đoạn mã này cho biết thêm một giá trị mới cho @traits với tên và giá trị nhất định. Điều đó có đúng không?
Nhờ sự giúp đỡ của bạn, đây là toàn bộ mã nguồn đó khiến tôi gặp khó khăn, cho bất cứ ai muốn nhìn thấy nó:
# 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
Và trong sử dụng:
class Dragon < Creature
life(1340) # tough scales
strength(451) # bristling veins
charisma(1020) # toothy smile
weapon(939) # fire breath
end
Đọc: http://yehudakatz.com/2009/11/15/metaprogramming-in-ruby-its-all-about-the-self/ – Phrogz
Cảm ơn, điều này có vẻ hữu ích. Nhưng tôi thực sự muốn hiểu ý nghĩa của def self.metaclass; lớp << tự; tự; kết thúc; kết thúc. – LonelyWebCrawler