How can I convert an array into a string that lists each item next to its position in the array?

53 views Asked by At

I would like to take an array... teams = ["Cowboys", "Heat", "Blue Devils"]

...and convert this to a string... # => "1. Cowboys 2. Heat 3. Blue Devils"

...and use string interpolation to concatenate it with another string.

# => "My three favorite teams: 1. Cowboys 2. Heat 3. Blue Devils"

2

There are 2 answers

0
DiegoSalazar On

Use each_with_index:

teams = ["Cowboys", "Heat", "Blue Devils"]
numbered = teams.each_with_index.map { |team, i| "#{i + 1}. #{team}" }.join(" ")
# => "1. Cowboys 2. Heat 3. Blue Devils"

Then you can interpolate:

fave_teams = "My #{teams.size} favorite teams: #{numbered}"

each_with_index adds the position of each element and returns an enumerator that you can map over with a block. The block receives each item and its index.

0
B Seven On
teams.map.with_index(1) do |t, i|
  "#{ i }. #{ t }"
end.join( ' ' )