Array in Ruby

2023-10-16 hit count image

Let's see how to use Array in Ruby.

Outline

In this blog, you’ll see how to use Array in Ruby.

Basic usage

You can define and use the array like the below.

cats = ['Nabi', 'Mini', 'Kitty']
puts cat[0]
# Navi

Like other languages, the Ruby array index is also started 0.

Array.new

Below is the easiest way to define the array.

cats = ['Nabi', 'Mini', 'Kitty']

But, you can also use Array.new to make an array.

cats = Array.new
# []

If you define with no parameter like above, the 0 element array is created.

cats = Array.new(2)
# [nil, nil]

If you set one parameter like above, the array is created with the size of the number, and filled nil.

cats = Array.new(3, 1)
# [1, 1, 1]

If you define the array as above, the array has 3 elements filled 1 value.

Array size

You can use size / length to get the array size.

cats = ['Nabi', 'Mini', 'Kitty']
cats.size
# 3

You can use length as below.

cats = ['Nabi', 'Mini', 'Kitty']
cats.length
# 3

Clear array

You can use the clear function to delete all values in the array.

cats = ['Nabi', 'Mini', 'Kitty']
cats.clear
# []

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts