Ruby 使用 each_with_index
Ruby using each_with_index
我希望此方法遍历名称数组 katz_deli
中的每个项目,并使用 puts
显示名称及其索引。但是,输出只是数组中的 first 名称及其索引。
我的代码:
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."
谢谢!
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
您可以先构建输出字符串,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)
我希望此方法遍历名称数组 katz_deli
中的每个项目,并使用 puts
显示名称及其索引。但是,输出只是数组中的 first 名称及其索引。
我的代码:
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."
谢谢!
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
您可以先构建输出字符串,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)