Open In App

How to map/collect with index in Ruby?

Mapping or collecting elements with their corresponding indices in Ruby is a common requirement in various programming scenarios. Ruby provides several options to suit your needs.

Let's explore four approaches to map or collect elements with their indices:

Approach 1: Using each_with_index

Below is the Code:

array = ["a", "b", "c"]
array.each_with_index do |element, index|
  puts "Element: #{element}, Index: #{index}"
end

Output
Element: a, Index: 0
Element: b, Index: 1
Element: c, Index: 2

Explanation:

Approach 2: Using map.with_index

Below is the Code:

array = ["a", "b", "c"]

mapped_array = array.map.with_index do |element, index|
  "Mapped Element #{index}: #{element}"
end

puts mapped_array

Output
Mapped Element 0: a
Mapped Element 1: b
Mapped Element 2: c

Explanation:

Approach 3: Using Enumerable#each_with_index

Below is the Code:

array = ["a", "b", "c"]

array.enum_for(:each_with_index).map do |element, index|
  puts "Element: #{element}, Index: #{index}"
end

Output
Element: a, Index: 0
Element: b, Index: 1
Element: c, Index: 2

Explanation:

Approach 4: Using Range#each_with_index

Below is the Code:

array = ["a", "b", "c"]

(0...array.length).each do |index|
  puts "Element: #{array[index]}, Index: #{index}"
end

Output
Element: a, Index: 0
Element: b, Index: 1
Element: c, Index: 2

Explanation:

Conclusion

Mapping or collecting elements with their corresponding indices in Ruby provides flexibility and enhances the capability of handling data structures effectively.

Article Tags :