Array#size
collection.size -> integer Returns:
Integer · Updated March 13, 2026 · Array Methods collections length count size
The size method returns the number of elements in a collection. It’s defined on arrays, hashes, strings, and other enumerable objects.
With Arrays
[1, 2, 3].size # => 3
[].size # => 0
Array.new(10).size # => 10
With Hashes
{a: 1, b: 2}.size # => 2
{}.size # => 0
With Strings
"hello".size # => 5 (characters)
"hello".length # => 5
"".size # => 0
Practical Examples
Check if Empty
items = []
if items.size == 0
puts "No items"
end
# Or use empty?
if items.empty?
puts "No items"
end
Loop Bounds
data = [1, 2, 3, 4, 5]
data.size.times do |i|
puts "Index: #{i}"
end
Conditional Processing
results = fetch_results
if results.size > 10
puts "Warning: #{results.size} results found"
end
Chunk Processing
data = (1..100).to_a
chunk_size = data.size / 3
Comparison with length
# size and length are aliases for most collections
"hello".size # => 5
"hello".length # => 5
[1,2,3].size # => 3
[1,2,3].length # => 3
Performance
# For arrays and strings, size/length are O(1)
# Count iterates, so avoid for size checks
arr = [1,2,3]
arr.size # O(1), fast
arr.count # O(n), iterates
Custom Objects
class MyCollection
def initialize
@items = []
end
def <<(item)
@items << item
end
def size
@items.size
end
end
With Enumerators
# Enumerator with size (when known)
enum = (1..100).each
enum.size # => 100 (Ruby 2.5+)