From: Bill Atkins Date: 2005-06-06T00:19:12+09:00 Subject: Re: [QUIZ] [Solution] Whiteout (#34) if __FILE__ == $0 # invoked as an exectuable ARGV.each do |file| source = File.read(file) # save the shebang (if there is one) shebang = nil source.sub /^(\#!.*?)\n/ do |m| shebang = m; "" end # convert the remaining text to whitespace; a given line will # contain n spaces, where n is the ASCII code of the character # that line represents tabs (\t) are used to represent 16 spaces result = source.split(//).collect do |char| ascii = char[0] "\t" * (ascii / 16) + " " * (ascii % 16) end.join "\n" result = "require 'whiteout'\n" + result File.open file, "w" do |f| f.write result end end else # required as a library source = File.read $PROGRAM_NAME source.sub! /^.*?require 'whiteout'\n/, "" result = source.split(/\n/).collect do |line| ascii = 0 line.each_byte do |c| if c.chr == "\t" ascii += 16 elsif c.chr == " " ascii += 1 else raise "invalid input: #{c.chr}" end end ascii.chr end.join "" eval result end On 6/5/05, Dave Burt wrote: > "Robin Stocker" solved: > > Here's my solution for Ruby Quiz #34. It's my first one :) > > Welcome to Ruby Quiz, Robin! > > Here's my solution, which is basically the same as Robin's. I must cite > NegaPosi by SASADA Koichi for inspiration. > > http://www.dave.burt.id.au/ruby/whiteout.rb > > Known bug: "__END__" doesn't work in an eval'd string. No solution > anticipated. NegaPosi has this problem too. > > Also, my Whiteout doesn't try and detect whether the given file is a valid > whiteout file or not, so you'll get a syntax error if you "require > 'whiteout'" with anything else other that a shebang and whitespace in the > file. > > There's an interesting hack at the eval end of my script to make "if $0 == > __FILE__" blocks work: > eval "$0 = __FILE__; #{ Whiteout.decode(File.read($0)) }" > > Cheers, > Dave > > > > -- Bill Atkins