【发布时间】: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