0

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!

3
  • are you sure that you have more than one element in your array? if yes, please provide an example of your array's data Commented Nov 20, 2015 at 19:48
  • 2
    I cannot reproduce your problem. When I call line([ "Logan", "Avi", "Spencer" ]) I get three lines of output: The line is currently: 1. Logan, The line is currently: 2. Avi, and The line is currently: 3. Spencer. Commented Nov 20, 2015 at 19:49
  • The array is katz_deli = ["Logan", "Avi", "Spencer"]. I see. Is there a way to get this get this all on one line---i.e for the output to be exactly The line is currently: 1. Logan 2. Avi 3. Spencer I'm doing this for a course and I think that's what the instructors are looking for. Thanks! Commented Nov 20, 2015 at 20:04

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.