2013-06-12 78 views
0

我做散列的一個子類,我希望能夠以填充最初使用的哈希,即:紅寶石:如何填充哈希的子類,從哈希

class HashSub < Hash 
    def initialize(old_hash) 
    ... 
    end 
end 

a = HashSub.new({'akey' => 'avalue'}) 

puts a['akey'] 

>> avalue 

由於Hash.new用不了哈希,實現這個最簡潔的方法是什麼?

回答

5

最乾淨的,以我的經驗,是獨自離開初始化和依賴類[]操作:

>> class SubHash < Hash; end 
=> nil 

>> a = Hash[{:a => :b}] 
=> {:a=>:b} 

>> a.class 
=> Hash 

>> b = SubHash[{:a => :b}] 
=> {:a=>:b} 

>> b.class 
=> SubHash 
0
H = Class.new Hash 
a = {a: 2, b: 3} 
b = H[ a ] 
b.class #=> H 
1

爲了提高對丹尼斯的回答,您可以別名類方法[]new

class SubHash < Hash; end 
    singleton_class{alias :new :[]} 
end 

SubHash.new(a: :b).class # => SubHash