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.
据我所知,你只能这样做:a.remove()但是我留下了一个空的[],我不想要那个,我希望它完全消失了。
4 个解决方案
#1
1
You can use delete_if
and match the first term to your argument:
您可以使用delete_if并将第一个术语与您的参数匹配:
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).
(我也把数组作为参数包含在内,因为你的帖子中的执行上下文不清楚)。
#2
1
Following up on @iamnotmaynard's suggestion:
跟进@ iamnotmaynard的建议:
arr.delete_if { |a| a[0] == 'test' }
#3
0
assoc
.
arr.delete(arr.assoc("test"))
#4
0
I had a similar need to remove one or more columns that matched a text pattern.
我有类似的需要删除一个或多个匹配文本模式的列。
col_to_delete = 'test'
arr = [['test','apples','pears'],[2,3,5],[3,6,8],[1,3,1]]
arr.transpose.collect{|a| a if (a[0] != col_to_delete)}.reject(&:nil?).transpose
=> [["apples", "pears"], [3, 5], [6, 8], [3, 1]]
#1
1
You can use delete_if
and match the first term to your argument:
您可以使用delete_if并将第一个术语与您的参数匹配:
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).
(我也把数组作为参数包含在内,因为你的帖子中的执行上下文不清楚)。
#2
1
Following up on @iamnotmaynard's suggestion:
跟进@ iamnotmaynard的建议:
arr.delete_if { |a| a[0] == 'test' }
#3
0
assoc
.
arr.delete(arr.assoc("test"))
#4
0
I had a similar need to remove one or more columns that matched a text pattern.
我有类似的需要删除一个或多个匹配文本模式的列。
col_to_delete = 'test'
arr = [['test','apples','pears'],[2,3,5],[3,6,8],[1,3,1]]
arr.transpose.collect{|a| a if (a[0] != col_to_delete)}.reject(&:nil?).transpose
=> [["apples", "pears"], [3, 5], [6, 8], [3, 1]]