Ruby arrays are ordered, any object's?? A collection of integer indices. The elements in each array are associated with an index mentioned.
The array subscript starts at 0, such as C or Java. The negative index assumes the end of the array---that is,-1 represents the array index of the last element,-2 is the next element of the last element in the array, and so on.
Ruby arrays can hold objects such as strings, integers, long integers, hashes, symbols, and even other array objects. Ruby arrays are not as strict as arrays in other languages. Ruby arrays grow automatically while adding elements.
To create an array:
There are a number of ways to create or initialize an array. One way is the new class method:
You can set the size of an array when the array is created:
The array names now has a size or length of 20 elements. You can return a method of the size or length of an array:
#!/usr/bin/ruby
names = Array.new
puts Names.size # This returns-puts Names.length
# This also returns 20
This will produce the following results:
You can specify each element in an array of values as follows:
#!/usr/bin/ruby
names = array.new (4, "Mac")
puts "#{names}"
This will produce the following results:
You can also use the new block to compute the padding for each element:
#!/usr/bin/ruby
nums = array.new (Ten) {|e| e = e * 2}
puts "#{nums}"
This will produce the following results:
There is another method, array, []. It works like this:
Nums = Array. [] (1, 2, 3, 4,5)
An array of another form is created as follows:
Nums = Array[1, 2, 3, 4,5]
Kernel module Ruby's core, there is an array of methods that accept only one parameter. Here the method scope creates an array of numbers as arguments:
#!/usr/bin/ruby
digits = Array (0..9)
puts "#{digits}"
This will produce the following results:
Array-built methods:
We need an array object to invoke an instance of the arrays method. As we can see, here is how the array object is created to create an instance:
Array. [](...) [or] Array[...] [or] [...]
This returns a new array to populate the given object. Now using the created object, we can call any available instance methods. For example:
#!/usr/bin/ruby
digits = Array (0..9)
num = digits.at (6)
puts "#{num}"
This will produce the following results:
For example:
Try the following examples to collect all kinds of data.
A = ["A", "B", "C"]
n = [
puts] a.pack ("a3a3a3") #=> "a b C"
puts A.pack ("A3A3A3")
#=> "a\000\000b\000\000c\000\000"
puts N.pack ("CCC") #=> "ABC"
This will produce the following results: