Arlen Cuss
4/25/2008 12:48:00 AM
[Note: parts of this message were removed to make it a legal post.]
Hi,
On Fri, Apr 25, 2008 at 10:25 AM, John <john.d.perkins@gmail.com> wrote:
> Maybe someone sees how I can transform this into the nested array I
> need. If so, your help is appriciated.
>
>
celtic@sohma:~$ cat migratus.rb
def transform_nested data
result = {:name => "root", :elements => []}
data.each do |item|
index = result
item.each do |sub|
sub.gsub! /:$/, ''
new_index = index[:elements].find {|e| e[:name] == sub}
unless new_index
new_index = {:name => sub, :elements => []}
index[:elements] << new_index
end
index = new_index
end
end
result
end
data = [[".", "Migratus:"], [".", "Migratus", "app:"], [".", "Migratus",
"app", "controllers:"], [".", "Migratus", "app", "helpers:"], [".",
"Migratus", "app", "models:"], [".", "Migratus", "app", "views:"],
[".", "Migratus", "app", "views", "layouts:"], [".", "Migratus",
"app", "views", "projects:"], [".", "Migratus", "app", "views",
"tasks:"], [".", "Migratus", "backup-sunday:"], [".", "Migratus",
"config:"]]
require 'pp'
pp transform_nested(data)
celtic@sohma:~$ ruby migratus.rb
{:elements=>
[{:elements=>
[{:elements=>
[{:elements=>
[{:elements=>[], :name=>"controllers"},
{:elements=>[], :name=>"helpers"},
{:elements=>[], :name=>"models"},
{:elements=>
[{:elements=>[], :name=>"layouts"},
{:elements=>[], :name=>"projects"},
{:elements=>[], :name=>"tasks"}],
:name=>"views"}],
:name=>"app"},
{:elements=>[], :name=>"backup-sunday"},
{:elements=>[], :name=>"config"}],
:name=>"Migratus"}],
:name=>"."}],
:name=>"root"}
celtic@sohma:~$
The data may be hard to visualise in that way (I also stripped the ending
`:'s from some items so there were no duplicates), but basically we have the
result item `result':
result[:name] == "root" [the root object]
result[:elements] contains the item with [:name] == ".", which in turn has
[:elements] with the item with name "Migratus", which has "app",
"backup-sunday", "config" - so, nested hashes and arrays, which you can
traverse to your own delight.
HTH!
Arlen