1

I just started learning Ruby/Rails, and am trying to write a program that builds an array, then formats the new array.

It works up to the second while, and, if I have an array already built, the second part works as well. Is there something I am leaving out?

chap = []
page = []
lineWidth = 80
x = 0
n = chap.length.to_i
puts 'chapter?'
chapter = gets.chomp
while chapter != ''
  chap.push chapter
  puts 'page?'
  pg = gets.chomp
  page.push pg
  puts 'chapter?'
  chapter = gets.chomp
end
puts ('Table of Contents').center lineWidth
puts ''
while x < n
 puts ('Chapter ' + (x+1).to_s + ' ' + chap[x]).ljust(lineWidth/2) +(' page ' + page[x]).rjust(lineWidth/2)
 x = x + 1
end

Thanks for your help!

2
  • the length n is calculated before actually building the chap array, therefore x == n == 0. Move n=chap.length.to_i to after the first while. Also you don't need to_i Commented Sep 24, 2013 at 17:51
  • As a note on style, chapter != '' is not very pretty. Better is something like !chapter.empty? where you're testing chapter itself, not doing a comparison against another string. x += 1 is also preferable to x = x + 1. Commented Sep 24, 2013 at 18:48

1 Answer 1

3

Simple pilot error: You called

n = chap.length.to_i

too early. You have to get the length of the chap list AFTER you put things in it. Move that line here:

    ...
    puts 'chapter?'
    chapter = gets.chomp
end
n = chap.length.to_i

puts ('Table of Contents').center lineWidth

and it works fine.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.