2
我已經看到類似的問題,但我想我需要一些更具體的代碼。基本上我從CSV文件中調用了該行,但現在我需要刪除被調用的行。聽起來很簡單,但我在這裏寫信,請求大家幫忙。我知道這裏有很多代碼,但我認爲越多越容易理解上下文。道歉,如果代碼中有太多的噪音。使用Ruby從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 但我不完全理解的答案,因此,爲什麼我在這裏。任何幫助深表感謝。
感謝您的答覆,我已經試過落實到我的代碼,這一點,但它是不完全的工作?我沒有收到任何錯誤,只是沒有做任何改變。我用我的CSV文件名替換了@csvfile位,並將:foo替換爲:username。還有什麼我需要做的? – thomasgee
@thomasgee - 你用真實的用戶名替換了'true'嗎? – seph
不能作爲選項,因爲我在csv文件中有多個用戶,您可以從代碼中看到(delete_input)引用所選用戶名(來自gets.chomp),然後通過代碼進行傳輸。 – thomasgee