Skip to content

Instantly share code, notes, and snippets.

@lgranger
Created September 28, 2015 00:23
Show Gist options
  • Save lgranger/4b56c7f10a29e7c34c56 to your computer and use it in GitHub Desktop.
Save lgranger/4b56c7f10a29e7c34c56 to your computer and use it in GitHub Desktop.
# Building and sorting an array. Write the program we talked about at the beginning of this chapter, one that asks us to type as many words as we want (one word per line, continuing until we just press Enter on an empty line) and then repeats the words back to us in alphabetical order. Make sure to test your program thoroughly; for example, does hitting Enter on an empty line always exit your program? Even on the first line? And the second? Hint: There’s a lovely array method that will give you a sorted version of an array: sort. Use it!
puts "Type as many lines as you want and I'll alphabetize them for you:"
my_array = Array.new
new_word = "a"
while new_word != ""
new_word = gets.chomp
my_array.push(new_word)
end
my_array.delete("")
puts "Your list:"
puts my_array.sort
# Table of contents, revisited. Rewrite your table of contents program on page 32. Start the program with an array holding all of the information for your table of contents (chapter names, page numbers, and so on). Then print out the information from the array in a beautifully formatted table of contents.
toc_array = ["\"The Book Of Mad Skilz\"", "Table of Contents", "Ch.1", "What are Mad Skilz?", "Pg. 1", "Ch.2", "How do I get Mad Skilz?", "Pg. 26", "Ch.3", "Showing Off Your Mad Skilz", "Pg. 52"]
puts toc_array[0..1].each {|x| x.center(100)}
ch = 2
title = 3
pg = 4
pg_ct = 20
while ch < 9
print toc_array[ch].ljust(10)
print toc_array[title]
puts toc_array[pg].rjust(pg_ct)
ch += 3
title += 3
pg += 3
pg_ct -= 3.5
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment