简体   繁体   English

Ruby:如何使Hash from path更可靠?

[英]Ruby: how to make a Hash from path more robust?

Assuming some hashes in the array only have path ab or {"a"=>{"b"=>"someanswer"}} , how do I make the below code robust enough to display the last element without dieing? 假设数组中的某些哈希仅具有路径ab或{"a"=>{"b"=>"someanswer"}} ,如何使以下代码足够健壮以显示最后一个元素而不会消失?

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

The specifications are not complete. 规格不完整。 Something like that? 这样的东西?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM