How to Use the Ruby size Method

09/24/2021

Contents

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

Using the size method

The size method is a built-in method in Ruby that returns the number of elements in an object. This method can be called on various objects, such as arrays, strings, hashes, and more.

Using the size method with arrays

Arrays are one of the most commonly used objects in Ruby, and the size method can be used to determine the number of elements in an array. To use the size method with an array, simply call the method on the array object:

my_array = [1, 2, 3, 4, 5]
puts my_array.size

This will output 5, which is the number of elements in the array.

Using the size method with strings

Strings are another commonly used object in Ruby, and the size method can be used to determine the length of a string. To use the size method with a string, simply call the method on the string object:

my_string = "Hello, world!"
puts my_string.size

This will output 13, which is the length of the string.

Using the size method with hashes

Hashes are another commonly used object in Ruby, and the size method can be used to determine the number of key-value pairs in a hash. To use the size method with a hash, simply call the method on the hash object:

my_hash = {name: "John", age: 30, city: "New York"}
puts my_hash.size

This will output 3, which is the number of key-value pairs in the hash.

Using the size method with other objects

The size method can also be used with other objects in Ruby, such as ranges and sets. To use the size method with a range, simply call the method on the range object:

my_range = (1..10)
puts my_range.size

This will output 10, which is the number of elements in the range.

To use the size method with a set, simply call the method on the set object:

require 'set'

my_set = Set.new([1, 2, 3, 4, 5])
puts my_set.size

This will output 5, which is the number of elements in the set.