我有一些代碼是這樣的:使用define_method和元編程在Ruby中動態定義實例方法?
class Country
attr_reader :name
def initialize
@name = "MyName".freeze
end
def government
@government ||= Government.new(self)
end
def symbols
@symbols ||= Symbols.new(self)
end
def economy
@economy ||= Economy.new(self)
end
def education
@education ||= Education.new(self)
end
def healthcare
@healthcare ||= Healthcare.new(self)
end
def holidays
@holidays ||= Holidays.new(self)
end
def religion
@religion ||= Religion.new(self)
end
end
我怎麼能動態創建的方法呢?我想:
class Country
attr_reader :name
COMPONENETS = %w(government symbols economy education healthcare holidays religion)
COMPONENETS.each do |m|
define_method(m) do |argument|
instance_variable_set("@#{m}",Object.const_get(m.capitalize).new(self))
end
end
def initialize
@name = "MyName".freeze
end
end
如果我嘗試:
puts Country.new.education.inspect
我得到以下錯誤:
country.rb:16:in `block (2 levels) in <class:Country>': wrong number of arguments (0 for 1) (ArgumentError)
from country.rb:27:in `<main>'
缺少什麼我在這裏?
爲什麼你會認爲你錯過了一些東西?是否有錯誤信息?如果是,那是什麼?輸出是不是你所期望的?如果是,輸出是什麼,輸出是什麼所期望的行爲?行爲不是你所期望的行爲嗎?如果是,行爲是什麼,你期望的行爲是什麼?沒有發生什麼事情?發生的事情不應該發生?是不是應該發生的事情?請提供一個最小的自包含測試用例,所述測試用例的輸入和預期輸出以及所有錯誤和警告的行爲。 –
我想我錯過了某些東西因爲我沒有得到預期的行爲我只是更新了錯誤我得到的任何線索 –
似乎是'self'這裏與'Country'類相關,而不是Country的實例,我應該如何解決? –