[SOLUTION] Text Munger #76


#1

This is my first Ruby Q. 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 :wink:

I was able to squeeze things down to 15 lines in the end.

Ruby Q. #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


#2

Here’s mine, it doesn’t do nifty accented characters, but on the
other hand at least numbers and underscores aren’t letters
usage: ruby scramble.rb < input.txt

% cat scramble.rb
STDIN.read.gsub(/(\b[A-Za-z])([A-Za-z’]*)([A-Za-z])/){[$1,$3,$2.split
(//).sort_by{rand}.join].values_at(0,2,1).join}.display


#3

My version features an un-munging mode and the use of procs and blocks
to keep DRY. It won’t shuffle letters, but it will leave numbers and
underscores alone, too.

http://www.dave.burt.id.au/ruby/text_munger.rb


#4

On Apr 23, 2006, at 11:20 AM, Dave B. wrote:

It won’t shuffle letters

Is there a missing word in there? (I hope…) :wink:

James Edward G. II


#5

On 4/24/06, James Edward G. II removed_email_address@domain.invalid wrote:

On Apr 23, 2006, at 11:20 AM, Dave B. wrote:

It won’t shuffle letters

Is there a missing word in there? (I hope…) :wink:

It won’t shuffle accented letters!

And, Gordon Thiesfield, very nice!

Cheers,
Dave