Guy
Guy

Reputation: 87

Delete an entire array in Ruby

I'm trying to find out if I can delete an array with a method called on itself. array.clear removes all elements, but not the array itself.

Context

Here is the context. I have a CSV file with no headers. I want to be able to delete a row given one value in the row. So, the user can pass me "Chocolate", I seach the CSV and delete the row with Chocolate as the first value.

CSV file

Chocolate, some description blah
Cheese, some description about this one

Ruby file

require 'csv'

def remove_recipe(recipe_name)
  CSV.foreach(csv_file_path, w+) do |row|
    row.clear??? if row[0] == recipe_name
  end
end

I could add a header but I'd like to know if it's possible without.

Ok, to describe the input and output as Sawa has asked: A user will input string "Chocolate". I will search the CSV file for that string. If present, I want to update the CSV file to remove the row containing that string.

Upvotes: 0

Views: 591

Answers (2)

Derek Wright
Derek Wright

Reputation: 1492

If you are looking to update the CSV file, then this is the cleanest solution I could come up with:

require "csv"

def remove_recipe(name)
  rows = CSV.read('test.csv')
  rows.reject! { |r| r[0] == name }
  out = rows.inject([]) { |csv, row| csv << CSV.generate_line(row) }.join("")
  File.open('test.csv', 'w+') { |file| file.write(out) }
end

remove_recipe('Chocolate')

Upvotes: 2

hoffm
hoffm

Reputation: 2436

Parse the CSV as an array of arrays and remove the elements you want to remove:

require "csv"

def remove_recipe(recipe_name)
  csv_ary = CSV.read("path/to/file.csv")
  cleaned_csv_ary = csv_ary.reject { |row| row[0] == recipe_name }
  # etc
end

Where I wrote "etc" you can use the cleaned array as you like, including converting it into a CSV string via #to_csv and writing it to a file.

Upvotes: 3

Related Questions