TheWebs TheWebs - 3 months ago 6
Ruby Question

Deleting an array from a multidimensional array in ruby

How would this get done? Assume I have the following

arr = [[test, 0, 0, 0], [apples, 0, 9, 8]]


I know I would do something like:

def delete_me(item)
arr.each do |a|
if a[0] == item
#delete the array containing test
end
end
end

delete_me('test')


As far as I can see you can only do:
a.remove()
but that leaves me with a empty
[]
,m I don't want that, I want it completely gone.

Answer

You can use delete_if and match the first term to your argument:

arr = [['test', 0, 0, 0], ['apples', 0, 9, 8]]

def delete_me(array, term)
  array.delete_if {|x, *_| x == term }
end

(I've included the array as an argument as well, as the execution context is not clear from your post).