2013-05-21 29 views

回答

6

只是出於好奇的緣故這裏的是另一種方法(一襯墊):

arr.transpose[0..-2].transpose 
+0

或只是'arr.transpose [2]'返回列。 –

+1

@MarkReed我寧願建議''''arr.transpose.last'''或'''arr.transpose [-1]'''作爲更通用的解決方案。 – Torimus

+0

@MarkReed我們有'Array#pop',它會很好的完成這項工作,因爲我發佈了。 :) –

1
arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]] 

i = 2 # the index of the column you want to delete 
arr.each do |row| 
    row.delete_at i 
end 

    => [["a", "b"], [2, 3], [3, 6], [1, 3]] 

class Matrix < Array 
    def delete_column(i) 
    arr.each do |row| 
     row.delete_at i 
    end 
    end 
end 
2

既然是剛剛過去的價值,你可以使用Array#pop

arr.each do |a| 
    a.pop 
end 

或者找到"c"的索引和索引中刪除的所有元素:

c_index = arr[0].index "c" 
arr.each do |a| 
    a.delete_at c_index 
end 

或者使用map

c_index = arr[0].index "c" 
arr.map{|a| a.delete_at c_index } 
1
arr.map { |row| row.delete_at(2) } 
#=> ["c", 5, 8, 1] 

這就是如果你真的想刪除最後一列,所以它不再在原始數組中。如果你只是想在離開arr原封不動地退回它

arr.map { |row| row[2] } 
#=> ["c", 5, 8, 1] 

如果你想刪除所有列對應於特定標題的元素:

if index = arr.index('c') then 
    arr.map { |row| row[index] } # or arr.map { |row| row.delete_at(index) } 
end 
+0

需要是'如果index = ARR [0]的.index( 'C')' –

0

假設數組的第一個元素總是一列列名,那麼你可以這樣做:

def delete_column(col, array) 
    index = array.first.index(col) 
    return unless index 
    array.each{ |a| a.delete_at(index) } 
end 

它會修改傳入的數組。你不應該把它的輸出分配給任何東西。

1
# Assuming first row are headers 
arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]] 

col = arr.first.index "c" 
arr.each { |a| a.delete_at(col) } 
0
arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]] 
arr.map(&:pop) 
p arr #=> [["a", "b"], [2, 3], [3, 6], [1, 3]] 
0

我有一個更通用需要刪除一個或多個列小號匹配一個文本模式(不只是刪除最後一列)。

col_to_delete = 'b' 
arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]] 
arr.transpose.collect{|a| a if (a[0] != col_to_delete)}.reject(&:nil?).transpose 
=> [["a", "c"], [2, 5], [3, 8], [1, 1]]