Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Text munga (See related posts)

This script is based on the Ruby quiz Text Munger:
http://www.rubyquiz.com/quiz76.html

It will scramble and print text from either a file or stdin

#!/usr/bin/ruby -w

require 'getoptlong'

class String
	def scramble
		self.split(/\b/).scramble_each.join
	end
end

class Array
	def scramble_each
		self.map do |word|
			word.split('').scramble
		end
	end
	def scramble
		first, last = self.shift, self.pop
		rest = self.sort_by { rand }
		"#{first}#{rest}#{last}"
	end
end

def from_file(file)
	if File.exist?(file)
		puts File.read(file).scramble
	else
		puts "File does not exist"
	end
end

def from_input
	print "'quit' to exit session\n> "
	loop do text = gets.chomp
		exit if text == 'quit'
		puts text.scramble
		print '> '
	end
end

opts = GetoptLong.new(
      [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
      [ '--file', '-f', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--input', '-i', GetoptLong::OPTIONAL_ARGUMENT ]
)

if ARGV.size == 0
	puts "Usage: #{$0} [OPTIONS]"
end

begin
	opts.each do |opt, arg|
		case opt
			when '--help'
				puts "-i\t\t- Read from input\n-f [FILE]\t- Read from file\n-h\t\t- Print this help message"
			when '--input'
				from_input
			when '--file'
				from_file(arg)
		end
	end
rescue GetoptLong::InvalidOption => e
	puts e
end

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts