[前][次][番号順一覧][スレッド一覧]

ruby-changes:15274

From: marcandre <ko1@a...>
Date: Fri, 2 Apr 2010 03:04:52 +0900 (JST)
Subject: [ruby-changes:15274] Ruby:r27158 (trunk): * lib/matrix.rb: New methods Matrix#each, #each_with_index, and

marcandre	2010-04-02 03:04:14 +0900 (Fri, 02 Apr 2010)

  New Revision: 27158

  http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=rev&revision=27158

  Log:
    * lib/matrix.rb: New methods Matrix#each, #each_with_index, and
      include Enumerable [ruby-core:28400]

  Modified files:
    trunk/lib/matrix.rb

Index: lib/matrix.rb
===================================================================
--- lib/matrix.rb	(revision 27157)
+++ lib/matrix.rb	(revision 27158)
@@ -65,6 +65,8 @@
 # * <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 @@
   @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 @@
   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

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]