Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method · added in Ruby 3.4
Array#fetch_values
(*::int indexes) -> self
fetch_values(*indexes) → new_array
fetch_values(*indexes) { |index| ... } → new_array
array.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.4.1/array.rb, line 210
def fetch_values(*indexes, &block)
indexes.map! { |i| fetch(i, &block) }
indexes
end
With no block given, returns a new array containing the elements of self at the offsets specified by indexes. Each of the indexes must be an integer-convertible object:
Example
a = [:foo, :bar, :baz] a.fetch_values(2, 0) # => [:baz, :foo] a.fetch_values(2.1, 0) # => [:baz, :foo] a.fetch_values # => []
For a negative index, counts backwards from the end of the array:
Example
a.fetch_values(-2, -1) # [:bar, :baz]
When no block is given, raises an exception if any index is out of range.
With a block given, for each index:
-
If the index is in range, uses an element of
self(as above). -
Otherwise, calls the block with the index and uses the block’s return value.
Example:
Example
a = [:foo, :bar, :baz] a.fetch_values(1, 0, 42, 777) { |index| index.to_s } # => [:bar, :foo, "42", "777"]
Related: see Methods for Fetching.
Ruby version changes
-
3.4
-
Array#fetch_valueswas added. [Feature #20702]
-