summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authormarcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2010-04-01 18:04:14 +0000
committermarcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2010-04-01 18:04:14 +0000
commit277cb36b21f8b5cb93e6b4373b23449bea917416 (patch)
tree164a3f1420bfe29c04b1f2732a43ebc433a4875b /lib
parentaf6e31b3444d090816e5c64e5827cd2271bc8bb3 (diff)
* 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
Diffstat (limited to 'lib')
-rw-r--r--lib/matrix.rb39
1 files changed, 39 insertions, 0 deletions
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
# * <tt> #column(j) </tt>
# * <tt> #collect </tt>
# * <tt> #map </tt>
+# * <tt> #each </tt>
+# * <tt> #each_with_index </tt>
# * <tt> #minor(*param) </tt>
#
# 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
@@ -340,6 +343,42 @@ class Matrix
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
# * col_range, row_range