From da4cfbf89ca9f87daa9ceef48c6bf15c6d7f9bcb Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Tue, 10 Sep 2024 10:22:34 +0900 Subject: [PATCH] mruby-array-ext: add a new method Array#fetch_values --- mrbgems/mruby-array-ext/mrblib/array.rb | 21 +++++++++++++++++++++ mrbgems/mruby-array-ext/test/array.rb | 7 +++++++ 2 files changed, 28 insertions(+) diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb index 1d10c6ef0..5c5d47fff 100644 --- a/mrbgems/mruby-array-ext/mrblib/array.rb +++ b/mrbgems/mruby-array-ext/mrblib/array.rb @@ -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 IndexError when one of indexes can't be found. + # Also see Array#values_at and Array#fetch. + # + # 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 diff --git a/mrbgems/mruby-array-ext/test/array.rb b/mrbgems/mruby-array-ext/test/array.rb index 5197c8cd2..fb0687521 100644 --- a/mrbgems/mruby-array-ext/test/array.rb +++ b/mrbgems/mruby-array-ext/test/array.rb @@ -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")