How to Find Length of Array in Ruby: Simple Guide
In Ruby, you can find the length of an array using the
length or size method. Both return the number of elements in the array as an integer.Syntax
To get the number of elements in an array, use the length or size method. Both work the same way.
array.length- returns the count of elements.array.size- alternative method, same result.
ruby
array = [1, 2, 3, 4] puts array.length puts array.size
Output
4
4
Example
This example shows how to create an array and find its length using length. It prints the number of elements.
ruby
fruits = ['apple', 'banana', 'cherry'] puts "The array has #{fruits.length} elements."
Output
The array has 3 elements.
Common Pitfalls
Sometimes beginners try to use count without arguments, which also works but is less common for length. Another mistake is calling length on a non-array object, which causes errors.
Also, length counts all elements, including nil values inside the array.
ruby
wrong = 12345 # wrong.length # This will cause an error because Integer has no length method array = [1, nil, 3] puts array.length # Counts nil as an element, output: 3
Output
3
Quick Reference
Use these methods to find array length:
| Method | Description |
|---|---|
array.length | Returns the number of elements in the array. |
array.size | Alias for length, same result. |
array.count | Counts elements, can take arguments to count specific items. |
Key Takeaways
Use
array.length or array.size to get the number of elements in a Ruby array.length counts all elements, including nil values inside the array.Avoid calling
length on non-array objects to prevent errors.count can also return length but is mainly for counting specific elements.Both
length and size methods are interchangeable for arrays.