Array in Ruby

BharteeTechRubyOnRails
2 min readJun 25, 2023

--

Arrays are ordered and integer-indexed collections of any object. Array indexing starts at
0, as in C or Java. A negative index is assumed to be relative to the end of the array; that is, an index of −1 indicates the last element of the array, −2 is the next to the last element in the array, and so on.

Class methods:

  1. []: Array[ h obj i ∗ ] → an_array
  2. Array.new ( size=0, obj= nil ) → an_array
  3. Array.new( array ) → an_array
  4. Array.new( size ) {| i | block } → an_array

[]: Array[ h obj i ∗ ] → an_array:

In this form the new array is empty.

Array.new
=> []

Array.new ( size=0, obj= nil ) → an_array:

It is created with size copies of the obj (that is, size references to the same obj).

Array.new(5, nil)
=> [nil, nil, nil, nil, nil]
Array.new(2, Hash.new)
=> [{}, {}]

Array.new( array )

The third form creates a copy of the array passed as a parameter (the array is generated by calling to_ary on the parameter).

Array.new(5)
=> [nil, nil, nil, nil, nil]

Array.new( size ) {| i | block }:

In the last form, an array of the given size is created.

Array.new(5) { |i| i*1}
=> [0, 1, 2, 3, 4]

3.0.0 :011 > Array.new(5) { |i| i*2}
=> [0, 2, 4, 6, 8]

Array using multiple instances:

a = Array.new(5) {Hash.new}  #here we used the block
=> [{}, {}, {}, {}, {}]

3.0.0 :004 > a[0]['cat'] = "minu"
=> "minu"

3.0.0 :005 > a
=> [{"cat"=>"minu"}, {}, {}, {}, {}]
b = Array.new(5, Hash.new) # here we declare the size and hash
=> [{}, {}, {}, {}, {}]

3.0.0 :007 > b[0]["cat"] = "minu"
=> "minu"

3.0.0 :008 > b
=> [{"cat"=>"minu"}, {"cat"=>"minu"}, {"cat"=>"minu"}, {"cat"=>"minu"}, {"cat"=>"minu"}]

--

--

BharteeTechRubyOnRails
BharteeTechRubyOnRails

Written by BharteeTechRubyOnRails

Ruby on Rails Developer || React Js || Rspec || Node Js

No responses yet