使用Ruby从CSV文件中删除行

时间:2016-10-02 02:43:03

标签: ruby csv

我已经看到了这个问题的类似答案,但我认为我需要一些更具体的代码。基本上我从CSV文件中调用了行,但现在我需要删除被调用的行。在我写这篇文章时听起来很简单,我要求大家帮忙。我知道这里有很多代码,但我认为越多,您就越容易理解上下文。如果代码中有太多噪音,请道歉。

def delete_user_menu
  puts "============================================"
  delete_users_active_list
  puts " "
  puts "Please type in the name of the user you wish to eradicate: "
  print "> "
  eradicate(gets.chomp)
end

def eradicate(delete_input)
  delete_row = delete_authentication(delete_input)
  if delete_row
    puts "Are you sure you want to delete #{delete_input} from the database?"
    puts "[y]es or [n]o"
    print "> "
    delete_answer = gets.chomp
    if delete_answer == "y"
      delete_user
      after_deletion_menu
    elsif delete_answer == "n"
      puts "Close call! Taking you back to main menu."
      sleep 2
      admin_main_menu
    else
      puts "Input not recognised. Please try again."
      eradicate(delete_input)
    end
  else
    puts "User not recognized. Please try again."
    sleep 1
    delete_user_menu
  end
end

def delete_user
  # this is where the delete user function needs to go
  after_deletion_menu
end

def after_deletion_menu
  puts " "
  puts "User deleted! What would you like to do now?"
  puts "1. Delete another user"
  puts "2. Back to main menu"
  print "> "
  after_deletion_choice = gets.chomp
  if after_deletion_choice == "1"
    delete_user_menu
  elsif after_deletion_choice == "2"
    admin_main_menu
  else
    puts "Input not recognized. Please try again."
    after_deletion_menu
  end
end

def delete_users_active_list
  CSV.foreach("./users.csv", headers: true) do |row|
    username = row['username']
    puts "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    puts "Username: #{username}"
  end
end

def delete_authentication(username)
  CSV.open('users.csv', headers: true).find { |row| row['username'] == username }
end

我看过这个问题How to remove a row from a CSV with Ruby 但我不完全理解答案,因此我在这里。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我查看了链接。首先,他们将整个csv文件读入table

table = CSV.table(@csvfile)

然后从table删除该行:

table.delete_if do |row|
  row[:foo] == 'true'
end

最后,他们用新的table减去行:

完全替换原始文件
File.open(@csvfile, 'w') do |f|
  f.write(table.to_csv)
end

这通常是您在处理文件时必须执行此类操作的方式。它不像数据库。

编辑 - 在你的情况下:

delete_user(delete_input)
...
def delete_user(user)
  ...
  table.delete_if { |row| row[:username] == user }
  ...