1 minute read

  1. Array = use
for num in [1,2,3]
  puts num
 end
[1,2,3].each {|num| do puts num}
  1. Array = CRUD

1) Create

Items can be added to the end of an array by using either push or «

arr = [1, 2, 3, 4]
arr.push(5) #=> [1, 2, 3, 4, 5]
arr << 6    #=> [1, 2, 3, 4, 5, 6]

unshift will add a new item to the beginning of an array.

arr.unshift(0) #=> [0, 1, 2, 3, 4, 5, 6]

With insert you can add a new element to an array at any position.

arr.insert(3, 'apple')  
#=> [0, 1, 2, 'apple', 3, 4, 5, 6]

Using the insert method, you can also insert multiple values at once:

arr.insert(3, 'orange', 'pear', 'grapefruit')
# => [0, 1, 2, "orange", "pear", "grapefruit", "apple", 3, 4, 5, 6]

2) Delete

You can call #delete on the array, passing it the item you want to delete as an argument

beatles = ["John", "Ringo", "Paul", "George"]
beatles.delete("John")
beatles     #=> ["Ringo", "Paul", "George"]

You can also call #delete_at on the array, passing it the index of item you want to delete as an argument

beatles = ["John", "Ringo", "Paul", "George"]
beatles.delete_at(0)
beatles     #=> ["Ringo", "Paul", "George"]

3) Update

array[index] = new_something

4) Read

delete with index number >> array.delete(18)
read   with index number >> array[18]

Categories:

Updated: