使用Ruby,我想在相應的getter中動態創建類級別的實例變量。對於其中的兩個,我使用attr_reader。但是,對於那些需要被初始化爲空數組,我做了以下內容:在ruby中動態定義memoized getter
class MatchMake
class << self
attr_reader :local_data, :remote_data
["type1", "type2"].each do |elem|
define_method "#{elem}_matches".to_sym do
instance_variable_set("@#{elem}_matches", [])
end
end
end
...
end
從我的理解這個代碼就相當於:
class MatchMake
class << self
def local_data
@local_data
end
def remote_data
@remote_data
end
def type1_matches
@type1_matches = []
end
def type2_matches
@type2_matches = []
end
end
...
end
首先,我想知道我是否糾正我的理解。其次,我想知道如果有memoize的變量的方式,如下面的:
所有的def type1_matches
@type1_matches ||= []
end
我的錯,我的C ode應該讀取def type1_matches,會編輯上面反映的問題。 –