> > 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. Let's apply some refactoring here. :-) > 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 > > def get_lengths(string) lens={} string.each_with_index do |line,i| lens[i] = line.index(/[^\s]/) end lens end def get_depths(lens) last_depth,depths=0,[] lens.sort {|a,b| a[1] <=>b[1]}.each do |line, depth| depth+=1 if depth > last_depth depths[line] = last_depth = depth end depths end def print_depths(string,depths) string.each_with_index do |line,i| print depths[i], " #{line}" end self end def get_depths (string) lens=get_lenghts(string) depths=get_depths(string,lens) print_depths(string,depths) end Well, that's it. Lots of refactoring. Mainly extract method, and better use of iterators. Fabio Mascarenhas mascarenhas / acm.org mascarenhas / elitenet.com.br