puts 'Type in as many words as you want. When finished press \'Enter\' on an empty line'
x = 0
word = 'word1'
array =[]
while word != ''
word = gets.chomp
array[x] = word
x = x + 1
end
puts ''
puts array.sort
A more straight-forward alternative, courtesy Adrian:
word = 'word'
words =[]
puts 'Please type as many words per line then press the Enter Key.'
puts 'When you are finished press the Enter Key without typing anything.'
while word != ''
word = gets.chomp
words = words.push word
end
puts ''
puts 'Your original values:'
puts words
puts ''
puts 'Your values sorted:'
puts words.sort
puts ''
. . . and another alternative, courtesy Stephen:
awords = []
word = "x"
puts "Type as many words as you want, or press \"enter\" to quit."
while word != ""
#get word from user
word = gets.chomp
#add to array
awords.push word
end
#user exited loop test for array before printing
if awords.empty?
puts "Now sorting what you typed.. thanks."
puts awords.sort
end
. . . one more from Joraaver:
puts "Type in as many words as you want. When you are done, press \'Enter'\ on the next line."
# array for the entries
words = []
entry = "0"
# taking responses and pushing them into the array
while entry != ""
entry = gets.chomp
words.push entry
end
# displaying data
puts "Thanks for your input. Sorting data ..."
puts words.sort
2. Rewrite table of contents program from p. 35 using arrays.
toc = ['Table of Contents', 'Chapter 1: Getting Started', 'page 1','Chapter 2: Numbers','page 9',
'Chapter 3: Letters','page 13']
page_width = 60
puts (toc[0].center(page_width))
puts ''
puts (toc[1].ljust(page_width/2) + toc[2].rjust(page_width/2))
puts (toc[3].ljust(page_width/2) + toc[4].rjust(page_width/2))
puts (toc[5].ljust(page_width/2) + toc[6].rjust(page_width/2))
Joraaver offers another solution:
toc = ["Table of Contents","Chapter 1: Getting Started", "page 1",
"Chapter 2: Numbers", "page 9", "Chapter 3: Letters", "page 13"]
line_width = 60
i = 0
puts(toc[0].center(line_width))
puts ""
# loop to define when to stop putting lines for the contents.
until i == 6
puts(toc[i += 1].ljust(line_width/2) + toc[i += 1].rjust(line_width/2))
end