summaryrefslogtreecommitdiff
path: root/array.rb
diff options
context:
space:
mode:
authorTakashi Kokubun <[email protected]>2024-01-23 12:09:57 -0800
committerGitHub <[email protected]>2024-01-23 20:09:57 +0000
commitc84237f9531aed3b204d3fdacc2dd9d2bd4c7d81 (patch)
tree924ec7260333bb75d8780e76325d5dd0303e0729 /array.rb
parent27c1dd8634d34bfe3592151d66b410f28ca749ce (diff)
Rewrite Array#each in Ruby using Primitive (#9533)
Diffstat (limited to 'array.rb')
-rw-r--r--array.rb55
1 files changed, 55 insertions, 0 deletions
diff --git a/array.rb b/array.rb
index d17f374235..e1ce6f49f9 100644
--- a/array.rb
+++ b/array.rb
@@ -1,5 +1,60 @@
class Array
# call-seq:
+ # array.each {|element| ... } -> self
+ # array.each -> Enumerator
+ #
+ # Iterates over array elements.
+ #
+ # When a block given, passes each successive array element to the block;
+ # returns +self+:
+ #
+ # a = [:foo, 'bar', 2]
+ # a.each {|element| puts "#{element.class} #{element}" }
+ #
+ # Output:
+ #
+ # Symbol foo
+ # String bar
+ # Integer 2
+ #
+ # Allows the array to be modified during iteration:
+ #
+ # a = [:foo, 'bar', 2]
+ # a.each {|element| puts element; a.clear if element.to_s.start_with?('b') }
+ #
+ # Output:
+ #
+ # foo
+ # bar
+ #
+ # When no block given, returns a new Enumerator:
+ # a = [:foo, 'bar', 2]
+ #
+ # e = a.each
+ # e # => #<Enumerator: [:foo, "bar", 2]:each>
+ # a1 = e.each {|element| puts "#{element.class} #{element}" }
+ #
+ # Output:
+ #
+ # Symbol foo
+ # String bar
+ # Integer 2
+ #
+ # Related: #each_index, #reverse_each.
+ def each
+ Primitive.attr! :inline_block
+ unless defined?(yield)
+ return to_enum(:each) { self.length }
+ end
+ _i = 0
+ value = nil
+ while Primitive.cexpr!(%q{ ary_fetch_next(self, LOCAL_PTR(_i), LOCAL_PTR(value)) })
+ yield value
+ end
+ self
+ end
+
+ # call-seq:
# array.shuffle!(random: Random) -> array
#
# Shuffles the elements of +self+ in place.