summaryrefslogtreecommitdiff
path: root/numeric.rb
diff options
context:
space:
mode:
authorTakashi Kokubun <takashikkbn@gmail.com>2023-09-07 10:57:52 -0700
committerGitHub <noreply@github.com>2023-09-07 10:57:52 -0700
commit5b5ae3d9e064e17e2a7d8d21d739fcc62ae1075c (patch)
treefde0e41fdd741cac9434969fa2d2a2df0d90e7e5 /numeric.rb
parent4efcaf956e27df365a1cf9e0cbb8d9a68eeb6995 (diff)
Rewrite Integer#times in Ruby (#8388)
Notes
Notes: Merged-By: k0kubun <takashikkbn@gmail.com>
Diffstat (limited to 'numeric.rb')
-rw-r--r--numeric.rb23
1 files changed, 23 insertions, 0 deletions
diff --git a/numeric.rb b/numeric.rb
index 806b65becd..3c059a58a4 100644
--- a/numeric.rb
+++ b/numeric.rb
@@ -217,6 +217,29 @@ class Integer
Primitive.cexpr! 'rb_int_size(self)'
end
+ # call-seq:
+ # times {|i| ... } -> self
+ # times -> enumerator
+ #
+ # Calls the given block +self+ times with each integer in <tt>(0..self-1)</tt>:
+ #
+ # a = []
+ # 5.times {|i| a.push(i) } # => 5
+ # a # => [0, 1, 2, 3, 4]
+ #
+ # With no block given, returns an Enumerator.
+ def times
+ unless block_given?
+ return to_enum(:times) { self < 0 ? 0 : self }
+ end
+ i = 0
+ while i < self
+ yield i
+ i = i.succ
+ end
+ self
+ end
+
# call-seq:
# to_i -> self
#