ruby - Modify multidimensional array of symbols -
at moment have like:
arr = [ :name, :address, cards_attributes: [ :last_name, :first_name, phones_attributes: [ :number, :_destroy ], emails_attributes: [ :number, :_destroy ], ... ] ]
... , want turn like:
arr = [ :id, # <- new! :name, :address, cards_attributes: [ :id, # <- new! :last_name, :first_name, phones_attributes: [ :id, # <- new! :number, :_destroy ], emails_attributes: [ :id, # <- new! :number, :_destroy ], ... ] ]
i know can add new symbol first level arr.push(:id)
how add elements sub hashes?
def add_id(collection) collection.unshift(:id) if collection.respond_to?(:unshift) collection.each |key, value| add_id(key) if key.respond_to?(:each) add_id(value) if value.respond_to?(:each) end end
edit: following update
"my question more how elegantly access sub hashes?"
we can use same general idea. didn't specify operation executed on hashes, method expect block:
def traverse(collection) yield collection if collection.is_a? hash collection.each |key, value| traverse(key) if key.respond_to?(:each) traverse(value) if value.respond_to?(:each) end end traverse(arr) { |hash| puts hash }
Comments
Post a Comment