Module: Babble

Defined in:
lib/babble/version.rb,
lib/babble.rb

Overview

:nodoc:

Defined Under Namespace

Modules: VERSION

Class Method Summary collapse

Class Method Details

.mainObject

Slurp argument files/standard input and output scrambled text.



5
6
7
# File 'lib/babble.rb', line 5

def Babble.main
	print scramble_text(gets(nil))
end

.parse_words(text) ⇒ Object

Split lines of text into ‘words’. (A ‘word’ may include formatting characters other than a space.) text.each should call a block with each line of text.



12
13
14
15
16
17
18
# File 'lib/babble.rb', line 12

def Babble.parse_words(text)
	words = []
	text.each do |line|
		line.split(/ /).each {|word| words << word}
	end
	words
end

.scramble(list, odds = 10) ⇒ Object

Scramble a list of items. odds is the likelihood that on encountering an item, it will jump to another occurrence of the same item.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/babble.rb', line 23

def Babble.scramble (list, odds = 10)

	#Build index of items.
	item_indices = Hash.new {|h, k| h[k] = Array.new}
	list.each_with_index {|item, index| item_indices[item].push(index)}
	
	#Loop through items, occasionally jumping to random occurrence of same item.
	index = 0
	scrambled_list = []
	while (index < list.length)
	
		#Get current item.
		item = list[index]
		
		#Add it to scrambled list.
		scrambled_list << item
		
		#If we should jump to another instance of the same item...
		if (rand(odds) >= odds - 1)
			#Choose a random occurrence of the same item.
			occurrence = rand(item_indices[item].length)
			index = item_indices[item][occurrence]
		end
		
		#Move to next item.
		index += 1
		
	end
	
	scrambled_list

end

.scramble_text(text, odds = 10) ⇒ Object

Scramble the given text.



58
59
60
61
62
63
64
65
# File 'lib/babble.rb', line 58

def Babble.scramble_text(text, odds = 10)
	scrambled_text = ""
	scramble(parse_words(text)).each do |word|
		scrambled_text += word
		scrambled_text += " " unless word =~ /\n$/
	end
	scrambled_text
end