ruby - 在 1.9.3 中读取文件时跳过第一行

标签 ruby rake-task ruby-1.9.3

我正在使用 ruby​​ 的文件打开并读取 rake 中的文本文件 任务。有没有一个设置可以指定我想要的第一行 文件被跳过? 到目前为止,这是我的代码:

desc "Import users." 
  task :import_users => :environment do 
    File.open("users.txt", "r", '\r').each do |line| 
      id, name, age, email = line.strip.split(',') 
      u = User.new(:id => id, :name => name, :age => age, :email => email) 
      u.save 
    end 
  end

我尝试了 line.lineno 也尝试了 File.open("users.txt", "r", '\r').each do |line, index|next if index == 0 但没有任何运气。

最佳答案

each 更改为 each_with_index do |line, index|next if index == 0 将起作用。

关于ruby - 在 1.9.3 中读取文件时跳过第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9614520/

相关文章:

ruby-on-rails - 删除了所有 Rails 迁移并删除了数据库

ruby-on-rails - NameError:未初始化的常量 Rails::TestTask

mysql - 对从 ActiveRecord 返回的结果强制排序

ruby - 如何在 ruby​​ 1.8.7 中写入 "string".encode ("us-ascii")?

ruby-on-rails - Ruby on Rails 版本之间的差异?我应该使用哪个?

ruby-on-rails - Rails 导出 CSV 忽略空白

ruby - 在 Mongoid 中,您可以原子地销毁嵌入文档并更新其父文档吗?

ruby-on-rails - rails 3.1 : how to run an initializer only for the web app (rails server/unicorn/etc)

ruby-on-rails - 如何在rake任务rails中使用current_user方法

Ruby Float#round 方法与 round(2) 的行为不正确