【问题标题】:Ruby cycle to alternate table row colors getting duplicatesRuby循环交替表格行颜色得到重复
【发布时间】:2016-01-29 02:17:35
【问题描述】:

我正在尝试每行交替颜色,但我得到重复的行

  def output_restaurant_table(restaurants=[])
    print " " + "Name".ljust(30)
    print " " + "Cuisine".ljust(20)
    print " " + "Price".rjust(26) + "\n"
    puts "-" * 80
    restaurants.each do |rest|
      line =  " " << rest.name.titleize.ljust(30)
      line << " " + rest.cuisine.titleize.ljust(20)
      line << " " + rest.formatted_price.rjust(26)

      x = [:red, :white]
      x.cycle(1) { |x|  output_action_header(line, :black, x) }

    end
    puts "No listings found" if restaurants.empty?
    puts "-" * 80
  end

如果我尝试将其移出

【问题讨论】:

  • 尝试将x = [:red, :white] 行移到restaurants.each 循环之外(在其上方)。如果我不得不猜测 - 因为那条线,每次你去另一家餐厅时它都会重新开始循环。
  • @TarynEast - 我认为你的评论应该作为答案发布,为了后代......
  • 这不太对。是的,它应该在循环之外,但它应该是x = [:red, :white].cycle,然后在循环内部,x.next
  • 谢谢,是的,我总是想等待并检查它是否有效,然后再将建议转化为答案:) Cary 是正确的,使用 next 是一种更好的编写方式......但是移动实例化循环之外是一个错误修复,它突出了原始代码的实际问题。
  • 至于接下来我只得到每一行之一,但颜色相同

标签: ruby duplicates row alternate


【解决方案1】:

如果我不得不猜测 - 因为那条线,每次你去另一家餐馆时它都会重新开始循环。

尝试将x = [:red, :white] 行移到restaurants.each 循环之外(在其上方)。

def output_restaurant_table(restaurants=[])
  print " " + "Name".ljust(30)
  print " " + "Cuisine".ljust(20)
  print " " + "Price".rjust(26) + "\n"
  puts "-" * 80
  # this is where you instantiate the set of things that will be cycled through.
  # You don't want to do this for every loop or the cycle will start over
  # every time you go through the loop (starting at the beginning every time)
  x = [:red, :white].cycle

  restaurants.each do |rest|
    line =  " " << rest.name.titleize.ljust(30)
    line << " " + rest.cuisine.titleize.ljust(20)
    line << " " + rest.formatted_price.rjust(26)

    # this is where you are saying "get me the next value of this cycle"
    x.next { |x|  output_action_header(line, :black, x) }

  end
  puts "No listings found" if restaurants.empty?
  puts "-" * 80
end

【讨论】:

  • 当它在餐厅外时,我会得到同一行的一个副本,否则我会得到一个副本
  • 好的,您需要实现解决方案的两个部分才能使其正常工作。把它移到外面,也可以按照 Cary 的建议改为使用“next”。
  • 当我将它移出并使用下一个时,我会从表中得到一行。
  • 我不明白你的意思。您能否更新您的问题并添加您更改的代码(将旧代码也保留在那里,只需添加您更改的代码)。
  • 好的,就像 .next 一样,如果它从里到外,我会得到相同的颜色,我会得到一行相同的颜色
猜你喜欢
  • 2016-07-08
  • 2011-10-07
  • 1970-01-01
  • 2013-05-12
  • 1970-01-01
  • 1970-01-01
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多