Search code examples
arraysrubyeachputs

Ruby using each_with_index


I'd like this method to circle through each item in the array of names katz_deli and use puts to display the name and its index. However, the output is just the first name in the array with its index.

My code:

def line (katz_deli)
  if katz_deli.count > 1
    katz_deli.each_with_index {|name, index| puts "The line is currently: #{index +1}. #{name}" }
  else
    puts "The line is currently empty."
  end
end

I want my output to be "The line is currently: 1. Logan 2. Avi 3. Spencer" But I'm getting "The line is currently: 1. Logan." Thanks!


Solution

  • You can build the output string at first, and puts it once it is ready:

    input = ["Logan", "Avi", "Spencer"]
    
    def line (katz_deli)
      if katz_deli.count > 1
        output = "The line is currently:"
        katz_deli.each_with_index do |name, index|
          output << " #{index +1}. #{name}"
        end
        puts output
      else
        puts "The line is currently empty."
      end
    end
    
    line(input)