diff options
author | Jean Boussier <[email protected]> | 2024-09-05 20:00:32 +0200 |
---|---|---|
committer | Jean Boussier <[email protected]> | 2024-09-06 12:40:32 +0200 |
commit | bc85c8d8529b58c5c649f418ca549569ba348caa (patch) | |
tree | bc86e51e3a4f61406b6dff7aea4eec17d441150f /array.rb | |
parent | 214668fccbca2db14ce57797017b34acd86d4690 (diff) |
Implement Array#fetch_values
[Feature #20702]
Works the same way than `Hash#fetch_values` for for array.
Notes
Notes:
Merged: https://github.com/ruby/ruby/pull/11557
Diffstat (limited to 'array.rb')
-rw-r--r-- | array.rb | 22 |
1 files changed, 22 insertions, 0 deletions
@@ -210,4 +210,26 @@ class Array end end end + + # call-seq: + # array.fetch_values(*indexes) -> new_array + # array.fetch_values(*indexes) {|key| ... } -> new_array + # + # Returns a new Array containing the values associated with the given indexes *indexes: + # a = [:foo, :bar, :baz] + # a.fetch_values(3, 1) # => [:baz, :foo] + # + # Returns a new empty Array if no arguments given. + # + # When a block is given, calls the block with each missing index, + # treating the block's return value as the value for that index: + # a = [:foo, :bar, :baz] + # values = a.fetch_values(1, 0, 42, 777) {|index| index.to_s} + # values # => [:bar, :foo, "42", "777"] + # + # When no block is given, raises an exception if any given key is not found. + def fetch_values(*indexes, &block) + indexes.map! { |i| fetch(i, &block) } + indexes + end end |