4

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
Nakilon
  • 34,866
  • 14
  • 107
  • 142
Bob.
  • 1,737
  • 1
  • 15
  • 20
  • Duplicate of [Automatic counter in Ruby for each?](http://stackoverflow.com/questions/533837/automatic-counter-in-ruby-for-each) – Andrew Grimm Nov 04 '10 at 22:45

3 Answers3

11
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]]
Nakilon
  • 34,866
  • 14
  • 107
  • 142
3

This can be done simply by using each_with_index:

 a.each_with_index{ |o,i| puts "position #{i} - letter #{o}" }
Sébastien Le Callonnec
  • 26,254
  • 8
  • 67
  • 80
1

You could do some times stuff. :)

array.length.times do |i|
  puts "Position: #{i} - Letter: #{array[i]}"
end

Note, i'm just learning Ruby -- this may be evil or something.

cHao
  • 84,970
  • 20
  • 145
  • 172
  • Generally you'll see Ruby code written to iterate directly over the array or container, rather than asking for the length. If we need an index value we'll use `each_with_index`. – the Tin Man Nov 05 '10 at 15:12
  • Thanks for the tip. I didn't know about `each_with_index`. I'd seem `times` before, though, so i used that. TMTOWTDI and stuff. :) – cHao Nov 05 '10 at 15:30