X
x1
Team:
I'm looking for a pragmatic way of creating a tree from a list of
items without knowing the depth of each.
For example:
max_depth = 4 #considers each unique item below the depth of 4 to be one
item_tree = {}
["CarRedFast",
"CarGreenSlow",
"Car",
"CarRedFastAgileSadCheeseBurger",
"CarRedFastAgileHappyJoy",
"GreenApplePie",
"GreenApple"
].each do |i|
items = i.gsub(/[A-Z][a-z]/) {|i| "_" + i}.gsub(/^_/, "").split("_")
end
This builds an array from items based on the case but many times, I
have needed to display this data in tree form as such:
#############################
# Desired output:
Car(2)
Red(1)
Fast(1)
Agile(2)
HappyJoy
SadCheeseBurger
Green(1)
Slow(0)
Green(1)
Apple(1)
Pie(0)
###############################
I've come across this numerous times and am pretty sure there's a
better way of doing it.
This is pretty much what I have now and it feels SO wrong to write!
#This just feels horrible writing
item_tree = {}
["CarRedFast",
"CarGreenSlow",
"Car",
"CarRedFastAgileSadCheeseBurger",
"CarRedFastAgileHappyJoy",
"GreenApplePie",
"GreenApple"
].each do |i|
items = i.gsub(/[A-Z][a-z]/) {|i| "_" + i}.gsub(/^_/, "").split("_")
items.each do |item|
if item_tree.include? item[0]
if item_tree[item[0]].include? item[1]
#yadadada
else
item_tree[item[0]][item[1]] = {}
end
else
item_tree[item[0]] = {}
end
end
end
Please.. Any suggestions at all.. All comments welcome!! TIA
I'm looking for a pragmatic way of creating a tree from a list of
items without knowing the depth of each.
For example:
max_depth = 4 #considers each unique item below the depth of 4 to be one
item_tree = {}
["CarRedFast",
"CarGreenSlow",
"Car",
"CarRedFastAgileSadCheeseBurger",
"CarRedFastAgileHappyJoy",
"GreenApplePie",
"GreenApple"
].each do |i|
items = i.gsub(/[A-Z][a-z]/) {|i| "_" + i}.gsub(/^_/, "").split("_")
end
This builds an array from items based on the case but many times, I
have needed to display this data in tree form as such:
#############################
# Desired output:
Car(2)
Red(1)
Fast(1)
Agile(2)
HappyJoy
SadCheeseBurger
Green(1)
Slow(0)
Green(1)
Apple(1)
Pie(0)
###############################
I've come across this numerous times and am pretty sure there's a
better way of doing it.
This is pretty much what I have now and it feels SO wrong to write!
#This just feels horrible writing
item_tree = {}
["CarRedFast",
"CarGreenSlow",
"Car",
"CarRedFastAgileSadCheeseBurger",
"CarRedFastAgileHappyJoy",
"GreenApplePie",
"GreenApple"
].each do |i|
items = i.gsub(/[A-Z][a-z]/) {|i| "_" + i}.gsub(/^_/, "").split("_")
items.each do |item|
if item_tree.include? item[0]
if item_tree[item[0]].include? item[1]
#yadadada
else
item_tree[item[0]][item[1]] = {}
end
else
item_tree[item[0]] = {}
end
end
end
Please.. Any suggestions at all.. All comments welcome!! TIA