map each with index

Ruby's map method, when used with the with_index method, allows you to iterate over an array and access both the elements and their respective indices. Here's a step-by-step explanation of how it works:

  1. Start with an array: Let's say we have an array called my_array with some elements: [10, 20, 30, 40, 50].

  2. Use the map method: Call the map method on the array and provide a block to define the transformation to be applied to each element. For example, we can square each element by writing my_array.map { |element| element 2 }.

  3. Add the with_index method: In order to access the index of each element, we chain the with_index method after the map method. This method takes an optional argument to specify the starting index. For example, my_array.map.with_index(1) { |element, index| ... } would start the index from 1 instead of the default 0.

  4. Access each element and index: Within the block, you can now access each element using the element variable and the index using the index variable. For example, my_array.map.with_index { |element, index| puts "Element #{element} is at index #{index}" }.

  5. Return the transformed array: The map method automatically collects the return values of each iteration and returns them as a new array. So, if you want to collect the squared elements, you can assign the result of the map method to a variable, like squared_array = my_array.map { |element| element 2 }.

That's it! By combining the map method with the with_index method, you can easily iterate over an array, access each element and its index, and perform transformations or collect the results.