Ruby Array Code Examples

Last Updated On Tuesday 25th Jan 2022
  • An array is an integer-indexed collection of any object.
  • An array can contain any data in it.
  • It can grow and shrink as data is inserted into it or removed from it.

Pushing an Element into an Array in Ruby

  • To Insert an element into an array, we can use Array << or Array push.
	nums = []

odds << 1
# [1]
odds << 3
# [1, 3]
odds.push 5
# [1, 3, 5]
	

Combing Two Arrays in Ruby

  • To combine two arrays, we can use the Array + operator.
	num1 = [1,3,5]
num2 = [2,4,6]

num1 + num2
# [1, 3, 5, 2, 4, 6]
	

Checking How Many Objects Are in the Array Ruby

  • Array also has Array length, Array size, and Array count, which all do the samething.

Determine how many objects/items are in the Array

	num1 = [1,3,5]
[num1.length, num1.size, num1.count]
# [3, 3, 3]
	

Checking Whether an Object Is in an Array Ruby

  • To check whether an array contains some object, we can use Array include.
	num = [1,2,3,4]

num.include? 1
# true
num.include? 5
# false
	

Accessing an Object of an Array Ruby

  • We can retrieve an item from an array using the square brackets ([]) method.
	numbers = [1, 3, 5, 7]
numbers[0]
# 1
numbers[1]
# 3
numbers[-1]
# 7
numbers[-2]
# 5
	

Filtering Items Using Array select Ruby

  • if we use Array select for filtering the items of an array.
	[1,2,3,4,5,6].select { |n| n.even? }