Ruby/Array/Push
Материал из Wiki.crossplatform.ru
Содержание |
Blow Your Stack
# A stack is a LIFO (last in, first out) structure. # You can use an array like a stack by using the push and pop methods from the Array class. fruit = %w[ apple orange banana ] fruit.pop # => "banana" p fruit # => ["apple", "orange" ] fruit.push "mango" p fruit # => ["apple", "orange", "mango"]
Push an array to another array
p a = [1,2,3] # => [1, 2, 3] p a << [4, 5, 6] # => [1, 2, 3, [4, 5, 6]] p a << a # => [1, 2, 3, [4, 5, 6], [...]]
Push integer and string to the same array
a = [1, 2, 3] # => [1, 2, 3] p a << 4.0 # => [1, 2, 3, 4.0] p a << "five" # => [1, 2, 3, 4.0, "five"]
With arrays,
# You can also use the push method, which is equivalent. x = [] x << "Word" puts x x.push "Word" puts x
You can add things to the end of the array by pushing data into it
x = [] x << "Word" puts x