I'm outputting a list of items from an array in Ruby. I need to output the position of each item in the array, as well as the value. I thought I was being clever by using the index of the value as I looped through the array rather then setting an temporary counter variable, but I got burned when I had an array with duplicate items. See below...
array = ["a","b","c","a"]
array.each do |letter|
puts "Position: #{array.index(letter)} - Letter: #{letter}"
end
# Position: 0 - Letter: a
# Position: 1 - Letter: b
# Position: 2 - Letter: c
# Position: 0 - Letter: a # Oops! That's not the position of that item.
Is below the most efficient way to generate the desired output or is there a better way that would keep the counter variable assignment contained within the each do loop?
array = ["a","b","c","a"]
counter = 0
array.each do |letter|
puts "Position: #{counter} - Letter: #{letter}"
counter += 1
end
# Position: 0 - Letter: a
# Position: 1 - Letter: b
# Position: 2 - Letter: c
# Position: 3 - Letter: a
array = ["a","b","c","a"]
array.each_with_index do |letter,i|
puts "Position: #{i} - Letter: #{letter}"
end
Also, if you will need to have this in map
method, you can use .with_index
modifier:
["a","b","c","a"].map.with_index { |e,i| [e,i] }
=> [["a", 0], ["b", 1], ["c", 2], ["a", 3]]
This can be done simply by using each_with_index
:
a.each_with_index{ |o,i| puts "position #{i} - letter #{o}" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With