← All languages
Ruby method of the day
Random

length

Return the number of elements in the array.

Description

The length method (also aliased as size) returns the number of elements in the array as an integer. For strings, it returns the number of characters.

This is a constant-time operation for arrays, as the count is stored internally. It does not iterate over the elements.

This is one of the most commonly used methods in Ruby for checking the size of collections and strings. It is interchangeable with size.

Example

[1, 2, 3].length       # 3
[].length               # 0
"hello".length          # 5

Reference