mruby-array-ext: add a new method Array#fetch_values

This commit is contained in:
Yukihiro "Matz" Matsumoto
2024-09-10 10:22:34 +09:00
parent 0972c84773
commit da4cfbf89c
2 changed files with 28 additions and 0 deletions
+21
View File
@@ -874,6 +874,27 @@ class Array
alias prepend unshift
alias filter! select!
##
# call-seq:
# ary.fetch_values(idx, ...) -> array
# ary.fetch_values(idx, ...) { |i| block } -> array
#
# Returns an array containing the values associated with the given indexes.
# but also raises <code>IndexError</code> when one of indexes can't be found.
# Also see <code>Array#values_at</code> and <code>Array#fetch</code>.
#
# a = ["cat", "dog", "cow"]
#
# a.fetch_values(2, 0) #=> ["cow", "cat"]
# a.fetch_values(2, 5) # raises KeyError
# a.fetch_values(2, 5) {|i| "BIRD" } #=> ["cow", "BIRD"]
#
def fetch_values(*idx, &block)
idx.map do |i|
self.fetch(i, &block)
end
end
##
# call-seq:
# ary.product(*arys) -> array
+7
View File
@@ -174,6 +174,13 @@ assert("Array#fetch") do
assert_raise(IndexError) { a.fetch(100) }
end
assert("Array#fetch_values") do
a = [ 11, 22, 33, 44 ]
assert_equal([33, 11], a.fetch_values(2, 0))
assert_raise(IndexError) { a.fetch_values(2, 5) }
assert_equal([33, 55], a.fetch_values(2, 5) { |i| i*11 })
end
assert("Array#fill") do
a = [ "a", "b", "c", "d" ]
assert_equal ["x", "x", "x", "x"], a.fill("x")