2011-12-13 97 views
1

考慮到我有這些散列:如何實現Hash#all?多維哈希?

h1 = {"a" => { "b" => 1, "c" => {"d" => 2, "e" => 3} } } 
h2 = {"a" => { "b" => 1, "c" => nil } } 

而且我希望這些結果:

h1.multi_all? # true 
h2.multi_all? # false 

我將如何實現multi_all方法?

回答

3
class Hash 
    def multi_all? &block 
    all? do |key, value| 
     if value.is_a?(Hash) 
     value.multi_all?(&block) 
     elsif block == nil 
     value 
     else 
     block[key, value] 
     end 
    end 
    end 
end 
2
class Hash 
    def values_r # recursive values 
    self.values.map do |x| 
     x.is_a?(Hash) ? x.values_r : x 
    end 
    end 
end 

h1.values_r.flatten.all? 

PS:你知道嗎all?方法也接受塊嗎?

+0

還是這樣? `class Hash def r_all? self.values.map do | x | x.is_a?(哈希)? x.r_all? :x end.all? 結束 結束` – maprihoda 2011-12-13 20:33:30

+0

您的變體忽略`&block` – 2011-12-13 20:50:11