diff --git a/lib/matrix.rb b/lib/matrix.rb index e69de29..e54f48a 100644 --- a/lib/matrix.rb +++ b/lib/matrix.rb @@ -0,0 +1,27 @@ +class Matrix + @matrix + + def initialize(string) + @matrix = string + end + + def extract_row(row_number) + array = [] + rows_of_matrix = @matrix.split("\n") + selected_row = rows_of_matrix[row_number] + selected_row.split(" ").each do |string| + array << string.to_i + end + array + end + + def extract_column(column_number) + array = [] + rows_of_matrix = @matrix.split("\n") + rows_of_matrix.each do |row| + array << row.split(" ")[column_number].to_i + end + array + end + +end \ No newline at end of file diff --git a/spec/matrix_spec.rb b/spec/matrix_spec.rb index e69de29..fd91f91 100644 --- a/spec/matrix_spec.rb +++ b/spec/matrix_spec.rb @@ -0,0 +1,38 @@ +require 'matrix.rb' +describe Matrix do + + context "when extracting a row of a matrix" do + it "returns [1, 2] as the first row of the matrix" do + matrix = Matrix.new("1 2\n10 20") + expect(matrix.extract_row(0)).to eq([1, 2]) + end + + it "returns [8, 6] as the second row of the matrix" do + matrix = Matrix.new("9 7\n8 6") + expect(matrix.extract_row(1)).to eq([8, 6]) + end + + it "returns [9, 8, 7] as the first row of the matrix" do + matrix = Matrix.new("9 8 7\n19 18 17") + expect(matrix.extract_row(0)).to eq([9, 8, 7]) + end + end + + context "when extracting a column of a matrix" do + it "returns [1 , 10] as the first column of the matrix" do + matrix = Matrix.new("1 2\n10 20") + expect(matrix.extract_column(0)).to eq([1, 10]) + end + + it "returns [5 , 20] as the second column of the matrix" do + matrix = Matrix.new("4 5\n19 20") + expect(matrix.extract_column(1)).to eq([5, 20]) + end + + it "returns [19, 13] as the second column of the non-regular matrix" do + matrix = Matrix.new("10 19 15\n11 13 16") + expect(matrix.extract_column(1)).to eq([19, 13]) + end + end +end +