How to Use the length Method in Ruby

09/21/2021

Contents

In this article, you will learn how to use the length method in Ruby.

The length Method

In Ruby, the length method is used to return the number of elements in a string, array, or other enumerable object. Here’s how to use it:

For Strings
string = "Hello, world!"
puts string.length # Output: 13
For Arrays
array = [1, 2, 3, 4, 5]
puts array.length # Output: 5
For Hashes
hash = { a: 1, b: 2, c: 3 }
puts hash.length # Output: 3
For Range
range = (1..10)
puts range.length # Output: 10

You can also use the size method, which is an alias for length and works in the same way:

string = "Hello, world!"
puts string.size # Output: 13

array = [1, 2, 3, 4, 5]
puts array.size # Output: 5

hash = { a: 1, b: 2, c: 3 }
puts hash.size # Output: 3

range = (1..10)
puts range.size # Output: 10
 

Here are some more details about using the length method in Ruby:

It works on any object that implements the Enumerable module

The length method can be called on any object that implements the Enumerable module, which includes many different types of collections in Ruby. Some examples include arrays, hashes, strings, ranges, and more.

It returns the number of elements in the collection

When called on a collection, the length method returns the number of elements in that collection. For example, if you call length on a string, it will return the number of characters in the string.

It is equivalent to the size method

The length method and the size method are essentially the same thing in Ruby. They both return the number of elements in a collection, and you can use either one depending on your personal preference.

It can be used with conditional statements

You can use the length method in conditional statements to check if a collection has a certain number of elements. For example:

my_array = [1, 2, 3, 4, 5]
if my_array.length > 3
  puts "This array has more than three elements."
else
  puts "This array has three or fewer elements."
end
It is a fast operation

The length method is generally very fast to execute, since it simply returns the size of a collection without having to iterate through its elements.