Monday, June 13, 2011

arrays and ranges

Thomson showed me today I can use a range for the 'do' keyword. so I can do something like...


(0..2).each do |i|


and this lets me create a set loop. I used this so I could use the each command when I wrote up arrays for the table of contents. So my whole program ended up like this:


chapter = ['Chapter 1: Getting Started', 'Chapter 2: Numbers', 'Chapter 3: Letters']
page = ['page 1', 'page 9', 'page 13']
line_width = 70
puts ('Table of Contents'.center(line_width))
chapter = ['Chapter 1: Getting Started', 'Chapter 2: Numbers', 'Chapter 3: Letters', 'Chapter 4: Variables and Assignent', 'Chapter 5: Mixing It Up', 'Chapter 6: More about Methods', 'Chapter 7: Flow Control', 'Chapter 8: Arrays and Iterators', 'Chapter 9: Writing Your Own Methods']
page = ['page 1', 'page 9', 'page 13', 'page 18', 'page 22', 'page 29', 'page 41', 'page 57', 'page 64']
(0..8).each do |i|
puts chapter[i].ljust(line_width/2) + page[i].rjust(line_width/2)
end


I also pushed a number game to github that I wrote as my final project tonight. It (I think) uses everything I've done from yesterday and today. It combines a few different ideas: using sort to organize guesses in an array, joining slots of an array with commas, branching to cover all possible responses with something appropriate. Not yet quite real-life Ruby scenario, but fun.

See you tomorrow!

No comments:

Post a Comment