鉴于我有这些哈希:
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方法?
答案 0 :(得分: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
答案 1 :(得分: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?
方法也接受一个块吗?