简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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