简体   繁体   中英

How do I implement Hash#all? for multidimensional hashes?

Given that I have these hashes:

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

And I want these results:

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

How would I implement the multi_all method?

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
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: do you know that all? method also accepts a block?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM