Wondering if someone could critique this code and give me the
"ruby way" of doing it. Basically, what it does it get the
"level" of different items in a menu based on the amount
of whitespace before the item. The code does function
properly, but I have a feeling I may be attacking this the
wrong way.
thanks,
-joe
def get_depths (string)
lastv = -1
i = 0
depth = 0
depths = []
lens = {}
# first get the depth of each line.
string.each do |line|
len = line =~ /^(\s+)/ ? $1.length : 0
lens[i] = len
i+=1
end
lens.sort {|a,b| a[1] <=>b[1]}.each do |k, v|
if(v > lastv)
depth+=1
end
lastv = v
depths[k] = depth
# print "k: #{k} v: #{v} d: #{depth}\n"
end
i=0
string.each do |line|
print depths[i], " #{line}"
i+=1
end
end
get_depths(<<EOF
text1@url1
text2@url2
text3@url3
text3.1 / url3.1
text3.2 / url3.2
text4@url4
text5@url5
text6@url6
text7@url7
text8@url8
text9@url9
EOF
)
prints:
1 text1@url1
2 text2@url2
3 text3@url3
4 text3.1 / url3.1
4 text3.2 / url3.2
5 text4@url4
4 text5@url5
5 text6@url6
4 text7@url7
4 text8@url8
1 text9@url9