Ruby Arrays

Array in Ruby programming is collection of an ordered object elements. This elements are used by index integer values. Ruby programming array is very flexible, There are possible to inserting similar and different data type element in array. Array elements are defined within the square brackets [] and two elements are separated by comma (,).

There are two way to create an array in ruby programming. Using literal constructor[] and second is Using the new class method.

Using literal constructor[]

#Create array element of integer value
arr_ints = [1,2,3,4,5]

#Create array which are store any object elements
arr_any  = [2020,true,"Code",'A',false,nil]

puts "#{arr_ints}" #Display all elements

puts "#{arr_any}" #Display all elements
[1, 2, 3, 4, 5]
[2020, true, "Code", "A", false, nil]
Ruby array example

Here arr_ints and arr_any are hold the reference of an array. element Index are start of 0 and upcoming element are index is rises by one.

#define array
arr_ints = [1,2,3,4,5]

puts arr_ints[0] #1

puts arr_ints[2] #3

puts arr_ints[1] #2

puts arr_ints[4] #5

puts arr_ints[3] #4

#when index is out of range
puts arr_ints[6] #nil  

There are possible to access random element of array by using index values. Because array is order elements. Note that last statement are not prints any value because given index value are out of range in array elements. The result of this program as follows.

1
3
2
5
4

So before use array element check that how many number of elements are exist in array. Get the length of array in following ways.

#Define array
arr_ints = [1,2,3,4,5]

arr_element = [0,1,2,4,5,7,8,9]
#Using length
puts arr_ints.length

#Using size
puts arr_element.size

length and size are method which are provide the how many element are store in particular array. In this example first array are contain 5 elements and second array are contains 8 elements. Output of this program.

5
8

Using of first and last method are retrieve the first and last elements of array.

#Retrieving First And Last Elements

arr_element = [1,2,3,4,5,6,7,8,9,10]

puts arr_element.first #1

puts arr_element.last #10
1
10

Using the new class method

#Create array using new class method 

#Empty array no parameter
arr_one = Array.new()

puts "#{arr_one}"
#First is size of array
#by default that each element are contain nil
arr_two =Array.new(4); 
puts "#{arr_two}"

#First is size of array
#Second parameter is default value, in this case default value is 1
arr_three = Array.new(3,1)
puts "#{arr_three}"

#First is size of array
#Second parameter is default array in this example
arr_four = Array.new(3,['Yes','No'])
puts "#{arr_four}"
Create Array by new class methodg
[]
[nil, nil, nil, nil]
[1, 1, 1]
[["Yes", "No"], ["Yes", "No"], ["Yes", "No"]]

In this last case each element are hold the same reference of array. See this example.

#Each element are hold the same reference of array
arr_four = Array.new(3,['Yes','No'])
puts "#{arr_four}"

#update values
arr_four[0][0]="Okay"

puts "#{arr_four}"
Modified Reference Array in ruby
[["Yes", "No"], ["Yes", "No"], ["Yes", "No"]]
[["Okay", "No"], ["Okay", "No"], ["Okay", "No"]]

Retrieving Multiple Elements:

#Retrieving Multiple Elements

arr_element = [1,2,3,4,5,6,7,8,9,10]

puts "#{arr_element[5,9]}" #[6, 7, 8, 9, 10]

puts "#{arr_element[1,3]}" #[2, 3, 4]
[6, 7, 8, 9, 10]
[2, 3, 4]

Nested or Multidimensional array

Array inside another array is called multidimensional array. Let see an example.

#Create nested array
arr_element = [1,2,3,[true,false,["Yes","No"],"Data"],20.4,645]

puts "#{arr_element}"
Nested or Multidimensional array
[1, 2, 3, [true, false, ["Yes", "No"], "Data"], 20.4, 645]

In there are question would be occurred in your mind how iterate an array elements which is form of nested multidimensional. Here given one solution.

#Display all array elements
#Which is exist in form of any dimensions 
def printData(arr)
  
  arr.each do |element|
    #When element is an array
    if(element.instance_of? Array)
        printData element
    else
        puts "#{element}"
    end
  end
end 

#Create nested array
arr_element = [1,2,3,[true,false,["Yes","No"],"Data"],20.4,645]

printData(arr_element)
1
2
3
true
false
Yes
No
Data
20.4
645

Ruby array methods

In this section given basic most common array method which is generally used in ruby programming language.

Method Overview
array.first returns first element of array, when array is not empty. Otherwise returns nil value
array.last returns last element of array, when array is not empty. Otherwise returns nil value
array.simple returns a random element of array
array.reverse returns a new array which contains reverse order element
array.sort Arranging array elements in Ascending order
array.include? Check if given element are exist in array. if element is exist then that is returns true value, otherwise returns false value.
array.at Getting array element by index, when index are invalid then this method is returning a nil value
array.take returns initial N elements of array
array.drop This are return all elements of array after N element
array.length, array.count, array.size return length of array
array.push Add element at the end of array
array.unshift Add element at the beginning of array
array.insert Inserting array element at given position
array.shift removing first element of array and returns deleted element value
array.pop removing last element of array and returns deleted element value
array.delete_at delete a element of array by index value
array.delete deleting all element of array by a given element value of array which is exist in array
array.uniq returning an array of unique elements

array.simple

simple method are gets random elements of an array. There are two variant one is without argument that are fetch and return one element.

#Get randomly single element 
code = ["C","C++","Java","Ruby","Swift","Python"]

puts "#{code.sample} Code " #display random element
Ruby Code

And second is parameterized method they are accepting one integer argument. This integer number indicates how many random element are retrieved . This second method are return an arrays.

#Get randomly mutiple elements 
code = ["C","C++","Java","Ruby","Swift","Python"]

puts "#{code.sample(3)} " #display random elements
["Python", "Swift", "Ruby"]

array.length, array.count, array.size

data = [1,2,3,[4,5,6,[7,8]]]

#find the length of array
puts data.length
puts data.count
puts data.size
4
4
4

Basic Operation of array

Split Array Elements Three are three ways to get particular portion of array.

#Split Array Elements

animal = ["Tiger","Bear","Crocodile","Gorilla","Lion","Giraffe","Elephant"]

set_one = animal[0,4]

set_two = animal.slice(1,6)

#Get N starting element
set_three = animal.take(3)  # N = 3

puts "Animal : #{animal}"
puts "Set One : #{set_one}"
puts "Set Two : #{set_two}"
puts "Set Three : #{set_three}"
Split Array Elements In Ruby Programming
Animal : ["Tiger", "Bear", "Crocodile", "Gorilla", "Lion", "Giraffe", "Elephant"]
Set One : ["Tiger", "Bear", "Crocodile", "Gorilla"]
Set Two : ["Bear", "Crocodile", "Gorilla", "Lion", "Giraffe", "Elephant"]
Set Three : ["Tiger", "Bear", "Crocodile"]

Select random element

#select random element of array
data = [1,2,3,4,5,6,7,8,9]

5.times{puts data[rand(0...data.length)]}
3
4
8
9
3


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved