From 277cb36b21f8b5cb93e6b4373b23449bea917416 Mon Sep 17 00:00:00 2001 From: marcandre Date: Thu, 1 Apr 2010 18:04:14 +0000 Subject: * lib/matrix.rb: New methods Matrix#each, #each_with_index, and include Enumerable [ruby-core:28400] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@27158 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- lib/matrix.rb | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'lib/matrix.rb') diff --git a/lib/matrix.rb b/lib/matrix.rb index f9c379509d..d131426f1a 100644 --- a/lib/matrix.rb +++ b/lib/matrix.rb @@ -65,6 +65,8 @@ end # * #column(j) # * #collect # * #map +# * #each +# * #each_with_index # * #minor(*param) # # Properties of a matrix: @@ -104,6 +106,7 @@ class Matrix @RCS_ID='-$Id: matrix.rb,v 1.13 2001/12/09 14:22:23 keiju Exp keiju $-' # extend Exception2MessageMapper + include Enumerable include ExceptionForMatrix # instance creations @@ -339,6 +342,42 @@ class Matrix end alias map collect + # + # Yields all elements of the matrix, starting with those of the first row, + # or returns an Enumerator is no block given + # Matrix[ [1,2], [3,4] ].each { |e| puts e } + # # => prints the numbers 1 to 4 + # + def each(&block) # :yield: e + return to_enum(:each) unless block_given? + @rows.each do |row| + row.each(&block) + end + self + end + + # + # Yields all elements of the matrix, starting with those of the first row, + # along with the row index and column index, + # or returns an Enumerator is no block given + # Matrix[ [1,2], [3,4] ].each_with_index do |e, row, col| + # puts "#{e} at #{row}, #{col}" + # end + # # => 1 at 0, 0 + # # => 2 at 0, 1 + # # => 3 at 1, 0 + # # => 4 at 1, 1 + # + def each_with_index(&block) # :yield: e, row, column + return to_enum(:each_with_index) unless block_given? + @rows.each_with_index do |row, row_index| + row.each_with_index do |e, col_index| + yield e, row_index, col_index + end + end + self + end + # # Returns a section of the matrix. The parameters are either: # * start_row, nrows, start_col, ncols; OR -- cgit v1.2.3