这是我的代码,它创建了20个项目的列表,我想将其拆分为2个10个列表,并且一次只显示一个列表。我怎样才能在红宝石中实现这一点?
def list_dogs
counter = 0
if counter <= 10
Dogs::DogsPopularity.all.each do |dog|
puts "#{counter +=1}. #{dog.name}"
#binding.pry
end
elsif counter > 10 && counter <= 20
Dogs::DogsPopularity.all.each do |dog|
puts "#{counter +=1}. #{dog.name}"
# binding.pry
end
end
#binding.pry
end
这就是打印出来的.....
答案 0 :(得分:0)
我们必须假设您的班级/模块返回20只狗,如果是这样的话:
def list_dogs
Dogs::DogsPopularity.all.each_slice(10).each do |dog_arr|
dog_arr.each_with_index do |dog, i|
puts "#{i+1}. #{dog.name}"
end
end
end
要看到这适用于基本数组,请参阅:
[*1..100].each_slice(10).each_with_index{|arr, i| puts "#{i+1}: #{arr}"}