Skip to Main Content
Learn to Program, 2nd Edition
book

Learn to Program, 2nd Edition

by Chris Pine
March 2009
Intermediate to advanced content levelIntermediate to advanced
194 pages
4h
English
Pragmatic Bookshelf
Content preview from Learn to Program, 2nd Edition

Exercises from Chapter 8

Building and Sorting an Array

How you could do it:

puts ​'Give me some words, and I will sort them:'
words = []
while​ true
word = gets.chomp
if​ word == ​''
break
end
words.push word
end
puts ​'Sweet! Here they are, sorted:'
puts words.sort
<= Give me some words, and I will sort them:
=> banana
=> apple
=> cherry
=> ​​
<= Sweet! Here they are, sorted:
 apple
 banana
 cherry

How I would do it:

puts ​'Give me some words, and I will sort them:'
words = []
while​ true
word = gets.chomp
break​ ​if​ word.empty?
words << word
end
puts ​'Sweet! Here they are, sorted:'
puts words.sort
<= Give me some words, and I will sort them:
=> banana
=> apple
=> cherry
=> ​​
<= Sweet! Here they are, sorted:
 apple
 banana
 cherry

Table of ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learn to Program, 3rd Edition

Learn to Program, 3rd Edition

Chris Pine
The Book of Ruby

The Book of Ruby

Huw Collingbourne

Publisher Resources

ISBN: 9781680500172Errata