Here is a method that do the job.
It recursively sort the hash using Array#sort and return the sorted array.
# Return array from hash recursively sorted
sort(&block).inject([]) do |array, (key, value)|
value = value.is_a?(Hash) ? value.to_sorted_array : value
array << [key, value]
end
end
end
hash={'user' => {'adress' => {'town' => 'Paris', 'street' => "rue de Quimper"}, 'name' => 'toto', 'age' => 12}}
hash.to_sorted_array # =>
[["user", [["adress", [["street", "rue de Quimper"], ["town", "Paris"]]], ["age", 12], ["name", "toto"]]]]
The Array#to_hash ruby standard method do not transform an array into an hash equivalent, recursively.
Here is a method which do the job:
# Recursively convert array to hash
inject({}) do |hash, (key, value)|
value = value.to_hash if value.kind_of?(Array)
hash.merge!({key => value})
end
end
end
array = [["user", [["adress", [["street", "rue de Quimper"], ["town", "Paris"]]], ["age", 12], ["name", "toto"]]]]
array.to_hash
{"user"=> {"name"=>"toto", "adress"=>{"street"=>"rue de Quimper", "town"=>"Paris"}, "age"=>12}}
I' ve put these extensions into a library on github : ruby_extensions
To install the gem :
Aucun commentaire:
Enregistrer un commentaire