Commit 70bbe9a8 authored by Jun Hiroe's avatar Jun Hiroe

Add Enumerable#reverse_each

parent 2ce23214
......@@ -498,4 +498,29 @@ module Enumerable
self.each {|*val| block.call(val.__svalue, obj) }
obj
end
##
# call-seq:
# enum.reverse_each { |item| block } -> enum
# enum.reverse_each -> an_enumerator
#
# Builds a temporary array and traverses that array in reverse order.
#
# If no block is given, an enumerator is returned instead.
#
# (1..3).reverse_each { |v| p v }
#
# produces:
#
# 3
# 2
# 1
#
def reverse_each(&block)
ary = []
self.each {|*val| ary.unshift(*val) }
ary.each {|*val| block.call(*val) }
self
end
end
......@@ -115,3 +115,10 @@ assert("Enumerable#each_with_object") do
assert_true [2, 4, 6, 8, 10, 12, 14, 16, 18, 20], (1..10).each_with_object([]) { |i, a| a << i*2 }
assert_raise(ArgumentError) { (1..10).each_with_object() { |i, a| a << i*2 } }
end
assert("Enumerable#reverse_each") do
r = (1..3)
a = []
assert_equal (1..3), r.reverse_each { |v| a << v }
assert_equal [3, 2, 1], a
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment