Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top