1

鉴于我有这些哈希:

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 方法?

4

2 回答 2

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
于 2011-12-13T20:09:56.710 回答
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?方法也接受一个块吗?

于 2011-12-13T20:09:11.407 回答