Стефан обнови решението на 21.10.2016 18:19 (преди около 8 години)
+class Hash
+ # this does not work for nested arrays
+ def fetch_deep!(roat)
+ keys = roat.split '.'
+ if keys.length == 1
+ # recursion bottom
+ self[keys[0].to_sym]
+ else
+ key = self[keys[0]] ? keys.shift : keys.shift.to_sym
+ self[key].fetch_deep! keys.join '.'
+ end
+ end
+
+ def extract_value(collection, key)
+ if collection.is_a?(Hash)
+ collection[key] ? collection[key] : collection[key.to_sym]
+ else
+ collection[key.to_i]
+ end
+ end
+
+ def fetch_deep(path)
+ keys = path.split '.'
+ key = keys.shift
+
+ new_collecton = extract_value(self, key)
+
+ until keys.empty?
+ key = keys.shift
+ new_collecton = extract_value(new_collecton, key)
+ end
+
+ new_collecton
+ end
+end
+
+order = {
+ dessert: {
+ type: 'cake',
+ variant: 'chocolate',
+ rating: 10,
+ comments: [
+ { text: 'So sweet!' },
+ { text: 'A perfect blend of milk chocolate and cookies.' }
+ ]
+ }
+}
+
+unless order.fetch_deep('false path').nil?
+ raise 'order.fetch_deep(dessert.comments.0.text) is wrong!'
+end
+
+unless order.fetch_deep('dessert.comments.0.text') == 'So sweet!'
+ raise 'order.fetch_deep(dessert.comments.0.text) is wrong!'
+end
+
+unless order.fetch_deep('dessert.variant') == 'chocolate'
+ raise 'order.fetch_deep(dessert.comments.0.text) is wrong!'
+end