0

我希望这种方法可以遍历名称数组中的每个项目katz_deli并用于puts显示名称及其索引。但是,输出只是数组中的第一个名称及其索引。

我的代码:

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

我希望我的输出是"The line is currently: 1. Logan 2. Avi 3. Spencer" 但我得到了"The line is currently: 1. Logan."谢谢!

4

2 回答 2

3

您可以首先构建输出字符串,puts一旦准备就绪:

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)
于 2015-11-20T20:30:52.320 回答
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
于 2015-11-20T20:27:19.960 回答