A so-called "array", an object that can store multiple objects.
irb(main):039:0> [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
You can add an object at the end using the push method.
irb(main):040:0> arr = []
=> []
irb(main):041:0> arr.push(100)
=> [100]
There are other notations to add at the end, so I will introduce them.
irb(main):046:0> arr = []
=> []
irb(main):047:0> arr << 100
=> [100]
First, let's make an Array normally. Try storing the string enclosed in single quotes in an Array.
irb(main):052:0> arr = ['String1', 'String']
=> ["String1", "String"]
irb(main):053:0> arr
=> ["String1", "String"]
However, it is troublesome to write single quotes often, so there is a notation **% w% [] **.
irb(main):057:0> arr = %w[String1 String2]
=> ["String1", "String2"]
irb(main):058:0> arr
=> ["String1", "String2"]
You can see that the result is the same as before. In an array enclosed in **% w **, the elements do not need to be enclosed in single quotes All you have to do is separate them with a space.
You can retrieve each element of the array using the each method.
irb(main):064:1* arr.each do |i|
irb(main):065:1* puts i
irb(main):066:0> end
1
2
3
4
5
=> [1, 2, 3, 4, 5]
You can use the map method to create a new array by processing each element of the array. For example, to make an array in which each element is multiplied by "2", write like this.
irb(main):068:0> arr = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
irb(main):069:0> arr.map { |i| i*2 }
=> [2, 4, 6, 8, 10]
You can store each element of the array in a variable using the following notation.
irb(main):074:0> arr = [1, 2]
=> [1, 2]
irb(main):075:0> foo, bar = arr
=> [1, 2]
irb(main):076:0> foo
=> 1
irb(main):077:0> bar
=> 2
You can see that foo and bar each contain the 0th and 1st of the array.
Recommended Posts