Skip to content

Latest commit

 

History

History
104 lines (84 loc) · 2.3 KB

array.adoc

File metadata and controls

104 lines (84 loc) · 2.3 KB

Array

Overview

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.

Notes

  • You can make an array by using square brackets, [ ]

  • First value in an array has index 0

  • The size and length 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

Try yourself

  • 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]
  1. Output is nil as it’s a way of saying nothing in Ruby

  2. 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

Next Topic

Proceed to Range

Previous Topic

Go back to Block

Table of Content