【问题标题】:CSV How to delete row depending of user choiceCSV 如何根据用户选择删除行
【发布时间】:2020-01-31 22:03:47
【问题描述】:

您好,我有一个程序,用户可以在其中编写八卦,其中包含作者和内容。我将其保存在 CSV 文件中。像这样:

author1,content1
author2,content2
author3,content3

我想通过简单的gets.to_i 询问用户他想删除哪一行。然后,如果用户输入2,则将删除第二行。如果他输入3 第三等... 如何根据用户选择删除 i 行?

【问题讨论】:

    标签: ruby csv model-view-controller delete-file


    【解决方案1】:

    你可以使用CSV::Table#delete

    i = gets.to_i
    table = CSV.table(file).by_row
    
    table.delete(i)
    

    【讨论】:

    • 我试过这个,我尝试修改你的答案,但没有奏效,有人有其他想法吗?
    【解决方案2】:

    如果这可以帮助某人,我已经找到了:

    def self.delete(index_to_delete)
        gossips = Gossip.all # Creation tempory array
        gossips.delete_at(index_to_delete - 1) # delete the choosen row
        File.open("db/gossip.csv", "w") do |f|
            f << ""         # clean csv file
        end
        gossips.map { |g| g.save } # save the new array as csv (with an other def to save)
    end
    

    我确信这不是最好的方法,但确实有效!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 2021-05-11
      相关资源
      最近更新 更多