An Array is just a list of items in order (like mangoes, apples, and oranges). Every slot in the list acts like a variable: you can see what object a particular slot points to, and you can make it point to a different object.
-
You can make an array by using square brackets,
[ ]
-
First value in an array has index 0
-
The
size
andlength
methods return the number of elements in an array -
Negative index values count from the end of the array, so last element is having index
-1
-
nil
is return if non-existent index no is being accessed ( index >= size ) -
Mutable and are dynamically resizable, append elements to them and they grow as needed
-
Array with similar object
var1 = ['Hello', 'Goodbye']
puts var1[0]
puts var1[1]
-
Array with different object
flavour = 'mango'
var2 = [80.5, flavour, [true, false]]
puts var2[2]
-
Array element addition
name = ['Satish', 'Talim', 'Ruby', 'Java',] # notice a trailing comma
puts name[0]
puts name[1]
puts name[2]
puts name[3]
# the next one outputs nil
# nil is Ruby's way of saying nothing
puts name[4] // (1)
name[4] = 'Pune'
puts name[4]
name[5] = 4.33 // (2)
puts name[5]
name[6] = [1, 2, 3] // (2)
puts name[6]
-
Output is nil as it’s a way of saying nothing in Ruby
-
We can other type of data too
-
Few methods on Array
newarr = [45, 23, 1, 90]
puts 'sort on array ==>>', newarr.sort
puts 'length on array ==>>', newarr.length
puts 'first element of array ==>>', newarr.first
puts 'last element of array ==>>', newarr.last
-
Iterator on Array
locations = ['Pune', 'Mumbai', 'Bangalore']
locations.each do |loc|
puts 'I love ' + loc + '!'
puts "Don't you?"
end
-
A small task
# Delete an entry in the middle and shift the remaining entries
locations.delete('Mumbai')
locations.each do |loc|
puts 'I love ' + loc + '!'
puts "Don't you?"
end
Proceed to Range
Go back to Block
Go to Table of Content