【问题标题】:Ruby using each_with_indexRuby 使用 each_with_index
【发布时间】:2016-02-23 10:11:10
【问题描述】:

我希望这种方法循环遍历名称数组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." 谢谢!

【问题讨论】:

  • 您确定数组中有多个元素吗?如果是,请提供数组数据的示例
  • 我无法重现您的问题。当我调用 line([ "Logan", "Avi", "Spencer" ]) 时,我得到三行输出:The line is currently: 1. LoganThe line is currently: 2. AviThe line is currently: 3. Spencer
  • 数组是 katz_deli = ["Logan", "Avi", "Spencer"]。我知道了。有没有办法让这一切都集中在一条线上——即输出正好是The line is currently: 1. Logan 2. Avi 3. Spencer 我正在为一门课程做这个,我认为这就是教师们正在寻找的。谢谢!

标签: arrays ruby each puts


【解决方案1】:

你可以先构建输出字符串,一旦准备好就可以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)

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 2011-08-04
      • 2015-05-08
      • 1970-01-01
      • 2016-01-31
      • 1970-01-01
      • 2012-06-04
      • 1970-01-01
      • 2014-10-23
      • 2017-05-28
      相关资源
      最近更新 更多