file.each_char在Ruby中的file.each_line之后不能正常工作

Mar*_*ski 1 ruby file

我试图file.each_char在a之后做file.each_line,但是当它像这样时它永远不会被调用.如果我摆脱了file.each_line,那么这个file.each_char电话就完美了.

这是我的代码供参考:

file.each_line do |line|
  if line =~ /^\s*$/
    next
  end
  lines += 1
end

file.each_char do |char|
  if char =~ /\s/
    next
  end
  chars += 1
end
Run Code Online (Sandbox Code Playgroud)

我怎样才能立即管理file.each_char通话file.each_line

Dyl*_*kow 6

当你运行时each_line,它会指向你的IO流的末尾(在这种情况下是一个文件).要再次遍历整个文件,您需要将其重置为指向流的开头.IO#rewind会为你做这件事:

file.each_line do |line|
  if line =~ /^\s*$/
    next
  end

  lines += 1
end

file.rewind

file.each_char do |char|
  if char =~ /\s/
    next
  end

  chars += 1
end
Run Code Online (Sandbox Code Playgroud)