From: "Guy N. Hurst" Date: 2001-03-24T18:29:27+09:00 Subject: [ruby-talk:13167] Re: Amusing contrast Dave Thomas wrote: > ... > No, but clarity and conciseness are not competing goals. I > deliberately wanted to see examples that were of comparable length to > the original. > > No takers? > Ok, I tried it... but there were ten lines, not twelve to start. And we still need a name for this process... > File.foreach($config || "config.status") do |$_| let's change from the virtual special variable '$_' to 'line' > next if /^#/ this is pointless, pitch it > if /^s%@(\w+)@%(.*)%g/ not much you can do here - it's a regex after all > name = $1 > val = $2 || "" In short code, why use this at all? They are only temp vars anyway > next if /^(INSTALL|DEFS|configure_input|srcdir)$/ =~ name will convert this to remove regex, replace with array method > val.gsub!(/\$\{([^{}]+)\}/) { "$(#{$1})" } > CONFIG[name] = val these can be combined since 'val' is only a temp var. Bang is spurious. Replacing the block would simplify things, too. > end > end Result: File.foreach($config || "config.status") do |line| if line =~ /^s%@(\w+)@%(.*)%g/ unless %w(INSTALL DEFS configure_input srcdir).include? $1 CONFIG[$1] = ($2||"").gsub(/\$\{([^{}]+)\}/, '$(\1)' ) end end end If you don't like line 4, using $1 and $2, or you wish to relocate as much character noise as possible, you may wish to do the following: config_file = $config || "config.status" line_regex = /^s%@(\w+)@%(.*)%g/ # two match results val_regex = /\$\{([^{}]+)\}/ # one match result File.foreach(config_file) { |line| if match_result = line_regex.match(line) name, val = match_result[1], (match_result[2] || "") # prevent nil for gsub unless %w(INSTALL DEFS configure_input srcdir).include? name CONFIG[name] = val.gsub(val_regex,'$(\1)') # \1 is the match end end } Guy N. Hurst -- HurstLinks Web Development http://www.hurstlinks.com/ Norfolk, VA 23510 (757)623-9688 FAX 623-0433 PHP/MySQL - Ruby/Perl - HTML/Javascript