From: Mike Date: 2006-04-23T23:58:32+09:00 Subject: [QUIZ][SOLUTION] Text Munger #76 ------=_NextPart_000_0039_01C666C4.88C40A10 Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit This is my first Ruby Quiz submission as well (there seems to be a lot of us this time through!). I'm going to attach the file because one line is crazy long and I don't want text wrapping to be a problem ;) I was able to squeeze things down to 15 lines in the end. # Ruby Quiz #76 - Text Munger by Michael Brum # # Usage: ruby rq76-munger.rb text_file.txt # # It seems to me that once a word gets past a certain length # the readability of that word once munged drops conciderably. # In trying to take that into account, for words over 8 characters # in length, I split the middle section into two strings and munge # those separately. def munge(word) case word.length when 0..3: return word when 4..8: return word[0].chr + word[1,(word.length-2)].split(//).to_a.sort_by{rand}.to_s + word[word.length-1].chr else return word[0].chr + word[1,(word.length/2)].split(//).to_a.sort_by{rand}.to_s + word[(word.length/2),(word.length-2)].split(//).to_a.sort_by{rand}.to_s + word[(word.length-1)].chr end end mtext = String.new() File.open(ARGV[0]) do |file| line = file.gets(separator=nil) line.split(/([^A-Za-z])/).each do |word| mtext += munge(word) end puts mtext end ------=_NextPart_000_0039_01C666C4.88C40A10 Content-Type: application/octet-stream; name="rq76-munger.rb" Content-Transfer-Encoding: quoted-printable Content-Disposition: attachment; filename="rq76-munger.rb" # Ruby Quiz #76 - Text Munger by Michael Brum #=20 # Usage: ruby rq76-munger.rb text_file.txt # # It seems to me that once a word gets past a certain length # the readability of that word once munged drops conciderably. # In trying to take that into account, for words over 8 characters # in length, I split the middle section into two strings and munge # those separately.=20 def munge(word) case word.length when 0..3: return word when 4..8: return word[0].chr + = word[1,(word.length-2)].split(//).to_a.sort_by{rand}.to_s + = word[word.length-1].chr else return word[0].chr + = word[1,(word.length/2)].split(//).to_a.sort_by{rand}.to_s + = word[(word.length/2),(word.length-2)].split(//).to_a.sort_by{rand}.to_s = + word[(word.length-1)].chr end end mtext =3D String.new() File.open(ARGV[0]) do |file| line =3D file.gets(separator=3Dnil) line.split(/([^A-Za-z])/).each do |word| mtext +=3D munge(word) end puts mtext end ------=_NextPart_000_0039_01C666C4.88C40A10--