Today I learned about arrays and their methods in Ruby.
Creating Arrays
Here are two basic arrays, created by an array literal:
num_array = [1, 2, 3, 4, 5]
str_array = ["This", "is", "a", "small", "array"]
Created with the Array.new
method. 2 optional arguments (initial size and default value):
Array.new #=> []
Array.new(2) #=> [nil, nil]
Array.new(3, 4) #=> [4, 4, 4]
Array.new(3, true) #=> [true, true, true]
Array.new also supports block:
Array.new(3) {|index| index * 2 } #=> [0, 2, 4]
Have to be used if default value is hash/array/object/etc. otherwise they'll share same reference:
# no!
arr = Array.new(3, {})
arr.first[:a] = 5
arr #=> [{:a=>5}, {:a=>5}, {:a=>5}]
# yes!
arr = Array.new(3) { {} }
arr.first[:a] = 5
arr #=> [{:a=>5}, {}, {}]
Accessing Elements
str_array = ["This", "is", "a", "small", "array"]
str_array.first #=> "This"
str_array.first(2) #=> ["This", "is"]
str_array.last(2) #=> ["small", "array"]
str_array[0] #=> "This"
str_array[1] #=> "is"
str_array[4] #=> "array"
str_array[-1] #=> "array"
str_array[-2] #=> "small"
Adding and Removing Elements
Adding: #push
method or the shovel operator <<
Removing: #pop
num_array = [1, 2]
num_array.push(3, 4) #=> [1, 2, 3, 4]
num_array << 5 #=> [1, 2, 3, 4, 5]
num_array.pop #=> 5
num_array #=> [1, 2, 3, 4]
Adding in the beginning: #unshift
Removing in the beginning: #shift
num_array = [2, 3, 4]
num_array.unshift(1) #=> [1, 2, 3, 4]
num_array.shift #=> 1
num_array #=> [2, 3, 4]
#pop
and #shift
can take integer arguments:
num_array = [1, 2, 3, 11, 12, 13]
num_array.pop(3) #=> [11, 12, 13]
num_array.shift(2) #=> [1, 2]
num_array #=> [3]
Adding and subtracting arrays
a = [1, 2, 3]
b = [3, 4, 5]
a + b #=> [1, 2, 3, 3, 4, 5]
a.concat(b) #=> [1, 2, 3, 3, 4, 5]
To find differences between arrays:
[1, 1, 1, 2, 2, 3, 4] - [1, 4] #=> [2, 2, 3]
Basic methods
[].empty? #=> true
[[]].empty? #=> false
[5, 6].empty? #=> false
[5, 6, 7].length #=> 3
[5, 6, 7].reverse #=> [7, 6, 5]
[5, 6, 7].include?(7) #=> true
[5, 6, 7].include?("7") #=> false
[5, 6, 7].join #=> "567"
[5, 6, 7].join("-") #=> "5-6-7"
Top comments (3)
Worth mention that Array.new also supports block:
and have to be used if default value is hash/array/object/etc. otherwise they'll share same reference.
Thanks! I will update the article with this changes!
Nice article!