Ruby从列表中保留计数

时间:2017-01-30 20:23:50

标签: ruby

我从列表中抓取一些数据,我想对这些项目进行排名。列表中有100个项目。当我运行我的代码时,我得到了我正在寻找的数据,但在我得到的每一个数据之前,我都得到了#34; 100"什么时候应该是" 1。 ...... ......"这是我的代码

lineList = mdoc.read.split("\n")
songList = []

count = 0

lineList.each do |line|
  matchObj = line.match(/<td>(\S+.+)<\/td>/)
  if matchObj then
    songList.push(matchObj.captures[0])
    count = count + 1
  end
end

songList.each do |title|
  puts count.to_s + ". " + title  
end

1 个答案:

答案 0 :(得分:3)

显示列表的典型方法是:

song_list.each_with_index do |song, i|
  puts '%d. %s' % [ i + 1, song ]
end

这使用字符串格式化函数%each_with_index