iterate an array of strings with index in ruby

To iterate an array of strings with their indexes in Ruby, use the "each_with_index" method. Here's an example:

main.rb
array = ["apple", "banana", "orange"]
array.each_with_index do |string, index|
  puts "Index #{index}: #{string}"
end
118 chars
5 lines

Output:

main.rb
Index 0: apple
Index 1: banana
Index 2: orange
47 chars
4 lines

In the example above, the "each_with_index" method is called on the "array" variable, and for each element in the array, the "do" block is executed. The "each_with_index" method passes a "string" variable and an "index" variable to the "do" block, which allows you to access both the string and its index within the block.

gistlibby LogSnag