Like many programming languages, Ruby also provides a complete data structure to store and manage the objects. Arrays are created using square brackets and a single object reference list separated by commas.
presidents=["John", "Richard", "Gerald", "Ronald", "George", "William"];
To make it easier to create an array full of words, Ruby provides a special flag to eliminate double quotes and commas, as shown in the following example:
presidents=%w[John Richard Gerald Ronald George William];
In other programming languages, the term "array" often means a set of objects of the same nature. But in Ruby, this is not the case. In Ruby, an "array" can be a collection of object references of a different nature. Therefore, the following are valid array representations:
Order_date=date.today ()
shirt_information=[14.5, "Long", 32,order_date]
In this array, object references are stored and indexed sequentially. Like Java, indexes start at 0, and indexes can be used to retrieve object references from an array. The following example requests the 3rd element in the Shirt_information array created above (the index is 2). Note that you can use the bracket flag or the At method to retrieve the object reference in the array.
IRB (main): 003:0> shirt_information[2]
=>
IRB (main): 004:0> shirt_information.at (2)
=> 32
Interestingly, you can also use a negative index to refer to an element in an array. A negative index is counted from the tail of the array.
IRB (main): 005:0> shirt_information[-3]
=> "Long"
Arrays are dynamic, meaning that the size of the groups can change dynamically depending on your actions. You can use the [index]= operator to add or replace elements in an array.
IRB (main): 013:0> shirt_information
=> [14.5, "Long", #<date:4907585/2,0,2299161>]
IRB (main): 014:0> shirt_information[1]= "Medium" #change shirt length
=> "Medium"
IRB (main): 015:0> shirt_information[4]=49.99 # Add shirt cost
=> 49.99
IRB (main): 016:0> shirt_information =>
[14.5, "Medium", #<date:4907585/2,0, 2299161>, 49.99]
You can also create a new array using a number pair and a portion of the array, using a start index, number of elements flag, or start index ... End index] flag.
IRB (main): 019:0> shirt_information
=> [14.5, Long, #<date:4907585/2,0,2299161>]
IRB (main): 0 20:0> shirt_dimensions = shirt_information[0,3]
=> [14.5, "Long",]
IRB (main): 021:0> Shirt_order = Shirt_ INFORMATION[2..5]
=> [#<date:4907585/2,0,2299161>, 49.99]
IRB (main): 030:0> shirt_information[-3,2 ]
=> [#<date:4907585/2,0,2299161>]