A Few Things to Try on 7. Arrays and Iterators

 Rubyでプログラミング勉強中(参照)。

 Arrays(配列)とIterators(イテレータ)について学ぶ。

A Few Things to Try on 7. Arrays and Iterators

一問目

Write the program we talked about at the very beginning of this chapter.

Hint: There’s a lovely array method which will give you a sorted version of an array: sort. Use it!

7. Arrays and Iterators

『Write the program we talked about at the very beginning of this chapter』っていうのは、以下。

Let’s write a program which asks us to type in as many words as we want (one word per line, continuing until we just press Enter on an empty line), and which then repeats the words back to us in alphabetical order.

7. Arrays and Iterators

これは簡単。

word = gets.chomp
ary = []
while word != ''
ary << word
word = gets.chomp
end
puts 'Sorted by Alphabet'
puts '=================='
puts ary.sort

二問目

Try writing the above program without using the sort method. A large part of programming is solving problems, so get all the practice you can!

7. Arrays and Iterators

これは難しかった・・・。ウンウンと唸って唸ってやっとできた。

word = gets.chomp
ary = []
while word != ''
ary << word
word = gets.chomp
end
i = 0
while i < ary.length
j = i + 1
while j < ary.length
if ( ary[i].to_s > ary[j].to_s )
tmp = ary[i]
ary[i] = ary[j]
ary[j] = tmp
end
j = j + 1
end
i = i + 1
end
puts
puts 'Sorted by Alphabet'
puts '=================='
puts ary

三問目

Rewrite your Table of Contents program (from the chapter on methods). Start the program with an array holding all of the information for your Table of Contents (chapter names, page numbers, etc.). Then print out the information from the array in a beautifully formatted Table of Contents.

7. Arrays and Iterators

こんな感じでよいのかな。

toc = ['Chapter 1:  Numbers  ', '  page 1',
'Chapter 2:  Letters  ', ' page 72',
'Chapter 3:  Variables', 'page 181']
lineWidth = 50
puts 'Table of Contents'.center(lineWidth)
puts ''
i = 0
j = 1
while i < toc.length
puts (toc[i].ljust(lineWidth/2) + toc[j].rjust(lineWidth/2))
i += 2
j += 2
end

雑感

 練習問題二問目が手強かったけど、勉強になった。次チャプター以降から、さらに深く(そして難しく)なっていく。ついていけるかな・・・。

See also

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.