mirror of
https://github.com/ruby/ruby.git
synced 2025-08-15 13:39:04 +02:00
Implement Array#fetch_values
[Feature #20702] Works the same way than `Hash#fetch_values` for for array.
This commit is contained in:
parent
214668fccb
commit
bc85c8d852
Notes:
git
2024-09-06 10:40:50 +00:00
2 changed files with 70 additions and 0 deletions
22
array.rb
22
array.rb
|
@ -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
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue