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.