1
+ #!usr/bin/env ruby
2
+
3
+ game_title = 'Ruby Blanks Game'
4
+
5
+ # Wraps the game title with dashes.
6
+ game_title = "| #{ game_title } |"
7
+ game_title . length . times do
8
+ print '-'
9
+ end
10
+
11
+ puts "\n #{ game_title } "
12
+
13
+ game_title . length . times do
14
+ print '-'
15
+ end
16
+ puts
17
+
18
+ # Sets a value to look for blanks in sentences.
19
+ BLANK_FLAG = '-----'
20
+ # Stores all sentences and types of blanks in a single place.
21
+ SENTENCES = [
22
+ {
23
+ :text => "I went to visit a #{ BLANK_FLAG } and found a #{ BLANK_FLAG } , it looked #{ BLANK_FLAG } so I started to #{ BLANK_FLAG } ." ,
24
+ :blanks => [ 'noun' , 'noun' , 'adjective' , 'verb' ]
25
+ } ,
26
+ {
27
+ :text => "Next thing you know, the #{ BLANK_FLAG } was having a #{ BLANK_FLAG } like everyone else. It was #{ BLANK_FLAG } and #{ BLANK_FLAG } ." ,
28
+ :blanks => [ 'noun' , 'verb' , 'adjective' , 'adjective' ]
29
+ }
30
+ ]
31
+
32
+ # Selects a random sentence from the available ones.
33
+ random_position = rand ( 0 ..( SENTENCES . length - 1 ) )
34
+ selected_sentence = SENTENCES [ random_position ]
35
+
36
+ # Prompts user to fill in the blanks, one by one.
37
+ # Assigns answers to a responses array.
38
+ # The array will have the same items as blanks as a map is being executed.
39
+ responses = selected_sentence [ :blanks ] . map do |blank |
40
+ indefinite_article = blank . start_with? ( 'a' ) ? 'an' : 'a'
41
+ print "Give me #{ indefinite_article } #{ blank } : "
42
+ response = gets . chomp
43
+ end
44
+
45
+ # Converts sentence into an array enumerable to become easier to iterate through.
46
+ selected_sentence [ :text ] = selected_sentence [ :text ] . split ( ' ' )
47
+
48
+ # This index is used to assign responses to the blanks.
49
+ index = -1
50
+ # Creates a sentence with the responses by checking if word has a a blank to be filled.
51
+ # It replaces only the blank with the response in order to keep punctuation, if existent.
52
+ complete_sentence = selected_sentence [ :text ] . map do |word |
53
+ if word . include? ( BLANK_FLAG )
54
+ index += 1
55
+ word . sub! ( BLANK_FLAG , responses [ index ] )
56
+ else
57
+ word
58
+ end
59
+ end
60
+
61
+ # Turns sentence into a string to be displayed to the user.
62
+ puts complete_sentence . join ( ' ' )
0 commit comments