forked from railsbridge/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharrays.step
93 lines (86 loc) · 2.41 KB
/
arrays.step
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
goals do
goal "Make some arrays and do stuff with them"
goal "Retrieve data from arrays"
end
step do
irb <<IRB
fruits = ["kiwi", "strawberry", "plum"]
IRB
message 'An array is a list of things in square brackets, separated by commas.'
message 'We generally call the individual things in an array **elements**.'
irb <<-IRB
things = [5, 'tree', 19.5]
things.length
IRB
message 'An array can contain all sorts of things, not just strings.'
message '`length` is a method that tells you how many **elements** are in an array.'
irb <<-IRB
empty_array = []
empty_array.length
IRB
message 'The simplest kind of array is the empty array.'
end
step do
irb <<IRB
fruits[0]
fruits[1]
fruits[2]
IRB
message 'Array elements are stored in order. You can retrieve them by using the square brackets to access them by their **index**.'
message 'Arrays are ordered: elements remain in the same order they started in.'
message 'Ruby starts counting at zero: the first element is `fruits[0]`.'
irb <<IRB
fruits.first
fruits.last
IRB
message 'Ruby gives us some helpful ways to get the first and last element from an array.'
end
step do
irb <<IRB
['salt'] + ['pepper']
IRB
message 'Arrays can be added together with the plus operator.'
irb <<IRB
fruits + ['mango']
fruits
IRB
message 'The plus operator doesn\'t modify the existing array, it makes a new one. How could you write that last piece of code to also modify the fruits array?'
end
step do
irb <<IRB
fruits = ["kiwi", "strawberry", "plum"]
fruits.push('apple')
fruits.pop()
IRB
message 'Ruby has many methods for modifying arrays. What did these two methods do?'
end
explanation do
message "Arrays are used whenever you need to work with a large group of similar items."
message 'A short list of methods for Array:'
table class: 'bordered' do
tr do
td 'length'
td 'how long is this array (how many elements)'
end
tr do
td 'first'
td 'get the first element of the array (same as array[0])'
end
tr do
td 'last'
td 'get the last element of the array (same as array[-1])'
end
tr do
td 'push'
td 'add a new element to the end of the array'
end
tr do
td 'pop'
td 'remove (and return) the element at the end of the array'
end
end
end
further_reading do
a "Ruby's documentation for Array", href: 'http://www.ruby-doc.org/core-1.9.3/Array.html'
end
next_step "hashes"