假设数组中的某些哈希只有路径a.b或{"a"=>{"b"=>"someanswer"}}
,如何使下面的代码足够健壮以显示最后一个元素而不会死?
path = ("a.b.c.d")
arrayOfHashes.collect {|hash| path.split(".").inject(hash) { |hash, key| hash[key] }}
答案 0 :(得分:0)
规格不完整。那样的东西?
arrayOfHashes = [{"a" => {"b" => "hello"}}, {"a" => {"b" => {"c" => {"d" => "response"}}}}]
path = "a.b.c.d"
arrayOfHashes.map do |hash|
path.split(".").inject(hash) do |acc, key|
acc.is_a?(Hash) ? acc[key] : acc
end
end
#=> ["hello", "response"]