deeps deeps - 6 months ago 12
Ruby Question

Remove elements from a hash array if a value matches a line in a text file

I have a JSON file with a hash in that looks like this

{
"1": {
"organisation": "Example1",
"name": "Name1",
"items": [
{
"name": "Name1",
"html_url": "URL1",
"results": [
"items go here"
]
},
{
"name": "Name2",
"html_url": "URL2",
"results": [
"Items go here"
]
},


I want to delete elements whose html_url matches a list stored in a text file, I have been toying with a delete-if like this.

@org.each do |key,value|
File.open('views/investigated.txt').each do |line|
value['items'].delete_if { |h| h['html_url'] == line }
end
end


but it doesn't seem to alter the array, I'm completely lost, any help would be much appreciated

Answer

@Stefan is right, it's better practice to create a separate array with the lines you'd like to delete from the array:

urls_to_delete = []
File.open('views/investigated.txt').each do |line|
    urls_to_delete.push(line)
end

Then use that array to remove the lines from the hash:

@org.each do |key,value|
    value['items'].delete_if { |h| urls_to_delete.include?(h['html_url']) }
end

Tested it with your example and does exactly what you're trying to achieve.