DEV Community

Cover image for fetch vs index methods when working with arrays in Ruby
Shkuryn
Shkuryn

Posted on

fetch vs index methods when working with arrays in Ruby

In the Ruby world, where many methods are provided for manipulating arrays, two of them - fetch and index - often raise questions among developers. Let's look at what the key differences between these methods are and in what situations it is better to use each of them.

fetch method
The fetch method in Ruby is used to retrieve a value from an array at a given index. Here are some key features of the fetch method:

arr = [1, 2, 3]
value = arr.fetch(5, "default_value") # returns "default_value"
Enter fullscreen mode Exit fullscreen mode

Setting the default value:
You can specify a default value as the second argument to the fetch method. If the index is outside the array, the default value will be returned.

arr = [1, 2, 3]
value = arr.fetch(1) # returns 2
Enter fullscreen mode Exit fullscreen mode

index method
The index method, on the other hand, is used to find the index of a given value in an array. Let's look at the key features of the index method:

Search value:
index looks for the first occurrence of a given value in the array and returns its index. If the value is not found, nil is returned.

arr = [1, 2, 3, 2]
index = arr.index(2) # Returns 1 (index of first occurrence of 2)
Enter fullscreen mode Exit fullscreen mode

Unhandled errors:
Unlike fetch, the index method does not handle array out-of-bounds errors. If the value is not found, nil is returned and you need to manually check for this value.

Example:

arr = [1, 2, 3]
index = arr.index(5) # Returns nil
Enter fullscreen mode Exit fullscreen mode

How to choose between fetch and index?

The choice between fetch and index depends on the task you are performing. If you need to get a value by index with the ability to set a default value, use fetch. If your goal is to find the index of a specific value in an array, index is your method.

Both methods provide varying levels of flexibility and can be a powerful tool in the hands of the developer. It is important to know their capabilities and choose the appropriate method for a specific task.

Top comments (0)