Skip to content

Commit 963420c

Browse files
committed
Arrays
1 parent 4a06557 commit 963420c

File tree

3 files changed

+87
-0
lines changed

3 files changed

+87
-0
lines changed

Arrays/array_methods.rb

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# each
2+
3+
languages = ['English', 'Romanian', 'Ruby']
4+
languages.each do |lang|
5+
puts 'I love ' + lang + '!'
6+
puts 'Don\'t you?'
7+
end
8+
puts 'And let\'s hear it for Java!'
9+
puts '<crickets chirp in the distance>'
10+
11+
# more iterators as integer method
12+
puts
13+
14+
3.times do
15+
puts 'Hip-Hip-Hooray!'
16+
end
17+
puts
18+
19+
2.times do
20+
puts '...you can say that again...'
21+
end
22+
puts
23+
24+
# to_s and join
25+
26+
foods = ['milk', 'bread', 'sugar']
27+
puts foods
28+
puts
29+
puts foods.to_s
30+
puts
31+
puts foods.join(', ')
32+
puts
33+
puts foods.join(' :) ') + ' 8)'
34+
200.times do
35+
puts []
36+
end
37+
puts
38+
39+
# push, pop, and last
40+
41+
favorites = []
42+
favorites.push 'raindrops on roses'
43+
favorites.push 'whiskey on kittens'
44+
45+
puts favorites[0]
46+
puts favorites.last
47+
puts favorites.length
48+
49+
puts favorites.pop
50+
puts favorites
51+
puts favorites.length

Arrays/ex_sorting.rb

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
=begin
2+
Building and sorting an array. Write a program that asks you to type as many words as you want (one word per line,
3+
continuing until you just press Enter on an empty line), and then repeat the words back to you in alphabetical order.
4+
=end
5+
6+
puts 'Type some words and I\'ll sort them for you.'
7+
words = []
8+
while true
9+
puts 'Write a word or just press Enter to see the result:'
10+
response = gets.chomp
11+
break if response.empty?
12+
words.push(response)
13+
end
14+
if words == []
15+
puts 'Nothing to sort.'
16+
else
17+
puts 'And there are your sorted words:'
18+
puts words.sort.join(', ')
19+
end
20+

Arrays/ex_table_of_contents_ver2.rb

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
=begin
2+
Table of Contents revisited. Rewrite your table of contents program. Start the program with an array holding all of the
3+
information for your table of contents(chapter names, page numbers, and so on). Then print out the information from the
4+
array in a beautifully formatted table of contents.
5+
=end
6+
7+
title = 'Table of Contents'
8+
chapters = [['Getting Started', 1], ['Numbers', 9], ['Letters', 13]]
9+
puts title.center(50)
10+
chap_number = 1
11+
chapters.each do |chap|
12+
left = 'Chapter ' + chap_number.to_s + ': ' + chap[0]
13+
right = 'page ' + chap[1].to_s
14+
puts left.ljust(30) + right.rjust(20)
15+
chap_number = chap_number + 1
16+
end

0 commit comments

Comments
 (0)