如何在Ruby中将20条数据的列表拆分为两个各10条的列表并分批展示?
解决Ruby列表拆分与分页展示的问题
嘿,我看了你的代码,发现问题出在counter的逻辑和遍历全部数据上——你现在的写法不管counter是多少,都会把所有20条狗都输出一遍,根本没做到拆分。咱们来改改,让它能分别展示前10条和后10条:
优化后的代码(支持分页展示)
def list_dogs(page = 1) # 获取所有狗狗数据 all_dogs = Dogs::DogsPopularity.all # 每页展示10条 dogs_per_page = 10 # 根据页码计算要展示的数据范围 start_position = (page - 1) * dogs_per_page end_position = start_position + dogs_per_page target_dogs = all_dogs[start_position...end_position] # 按顺序输出当前页的狗狗,计数从1开始 target_dogs.each_with_index do |dog, index| puts "#{index + 1}. #{dog.name}" end end
怎么用?
- 想展示前10条:直接调用
list_dogs(不传参数默认展示第1页) - 想展示后10条:调用
list_dogs(2)
为什么你的原代码不行?
你的原方法里,counter 是方法内部的局部变量,每次调用方法都会重置为0。而且不管counter的条件是什么,你都遍历了Dogs::DogsPopularity.all的所有数据,导致每次都会输出全部20条,完全没实现拆分的效果。
另一种更直白的写法(如果不需要分页扩展)
如果以后不需要支持更多页码,也可以直接拆成两个明确的逻辑:
def list_first_10_dogs Dogs::DogsPopularity.all.take(10).each_with_index do |dog, index| puts "#{index + 1}. #{dog.name}" end end def list_last_10_dogs Dogs::DogsPopularity.all.drop(10).each_with_index do |dog, index| puts "#{index + 1}. #{dog.name}" end end
调用 list_first_10_dogs 展示前10条,list_last_10_dogs 展示后10条就行。
内容的提问来源于stack exchange,提问作者michael pope
相关产品推荐
相关产品推荐

