Rubyハッシュの自動活性化を実装するために、次のクラスを使用できます。
class AutoHash < Hash
def initialize(*args)
super()
@update, @update_index = args[0][:update], args[0][:update_key] unless
args.empty?
end
def [](k)
if self.has_key?k
super(k)
else
AutoHash.new(:update => self, :update_key => k)
end
end
def []=(k, v)
@update[@update_index] = self if @update and @update_index
super
end
def few(n=0)
Array.new(n) { AutoHash.new }
end
end
このクラスでは、次のことができます
a = AutoHash.new
a[:a][:b] = 1
p a[:c] # => {} # key :c has not been created
p a # => {:a=>{:b=>1}} # note, that it does not have key :c
a,b,c = AutoHash.new.few 3
b[:d] = 1
p [a,b,c] # => [{}, {:d=>1}, {}] # hashes are independent
Joshuaによって提案されたこのクラスのもう少し高度な定義がありますが、これは私には理解するのが少し難しいです。
問題
新しいクラスを改善できると思う状況が1つあります。次のコードはエラーメッセージで失敗しますNoMethodError: undefined method '+' for {}:AutoHash
a = AutoHash.new
5.times { a[:sum] += 10 }
あなたはそれを処理するために何をしますか?[]+=
演算子を定義できますか?
関連する質問