新手问题 同一文件流只能遍历一次?

teddy · 2012年10月25日 · 最后由 5long 回复于 2012年10月25日 · 3137 次阅读
require "csv"

class EventManager

  def initialize
    puts "EventManager Initialized."
    filename = "event_attendees.csv"
    @file = CSV.open(filename)
  end



  def print_names
    @file.each do |line|
      puts line[2]
    end
  end

  def print_names2
    @file.each do |line|
      puts line[1]
    end
  end
end

manager = EventManager.new
manager.print_names
manager.print_names2

大家帮忙看看,只有第一个方法有输出,第二个就没了 puts @file 显示是同一个对象 如果每个方法都先 open file 的话是可以的,但是为什么每次 open 只能读取一次呢

是不是同一次 open 文件的话文件指针不会复位啊

对 C 底层不是很了解,只知道有 rewind 方法手动复位 http://apidock.com/ruby/v1_9_3_125/IO/rewind

和用 File 打开文件一样需要自己复位,调用 #rewind 方法就可以再用 #each 迭代了。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号