Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an alternative to using a counter variable in a each do loop in Ruby?

Tags:

ruby

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
like image 685
Bob. Avatar asked Dec 07 '22 00:12

Bob.


2 Answers

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]]
like image 64
Nakilon Avatar answered Dec 29 '22 00:12

Nakilon


This can be done simply by using each_with_index:

 a.each_with_index{ |o,i| puts "position #{i} - letter #{o}" }
like image 27
Sébastien Le Callonnec Avatar answered Dec 28 '22 23:12

Sébastien Le Callonnec