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?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top