I'd like to filter a 2 dimensional array taking the desired column indices and returning a 2d array with only those columns. Except on an empty array I'd like to return the same 2 dimensional array.
Also I don't want to modify the original array, and I'd like to write my code without any if statements, or limit branching as much as possible.
I'm wondering if it is redundant to Marshal#load
and Marshal#dump
and use #map!
.
There reason I chose to use #map!
is so I don't have to use an if..else..end
block, but I'm curious to learn other strategies.
Below is my solution:
def keep_columns args
matrix = Marshal.load Marshal.dump args[:matrix]
columns = args[:columns]
matrix.map! do |row|
row.select.with_index { |_,idx| columns.include? idx }
end unless columns.empty?
matrix
end
matrix = [['foo','bar', 'baz'],['cats', 'and', 'dogs']]
keep_columns matrix: matrix, columns: [0,2]
#=> [["foo", "baz"], ["cats", "dogs"]]
keep_columns matrix: matrix, columns: []
#=> [["foo", "bar", "baz"], ["cats", "and", "dogs"]]