Ruby:如何使路径中的Hash更健壮?

时间:2012-02-14 18:39:19

标签: ruby string hash dependency-injection

假设数组中的某些哈希只有路径a.b或{"a"=>{"b"=>"someanswer"}},如何使下面的代码足够健壮以显示最后一个元素而不会死?

path = ("a.b.c.d")
arrayOfHashes.collect {|hash| path.split(".").inject(hash) { |hash, key| hash[key] }}

1 个答案:

答案 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"]