Project

General

Profile

Actions

Feature #20702

closed

Add `Array#fetch_values`

Added by toy (Ivan Kuchin) 4 months ago. Updated 4 months ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:118969]

Description

Array and Hash have matching methods to fetch:

  • One value using [] (Array also allows fetching multiple with range or two arguments)
  • One value with default or exception using fetch method
  • Multiple values using values_at method

But only Hash has method fetch_values to fetch multiple values with fallback or raising an exception (see #10017).

hash = {a: 1, b: 2, c: 3}
array = [1, 2, 3]

hash[:b] # => 2
hash[:d] # => nil
array[1] # => 2
array[4] # => nil

hash.fetch(:b) # => 2
hash.fetch(:d) # => IndexError
hash.fetch(:d){ 42 } # => 42
array.fetch(1) # => 2
array.fetch(4) # => IndexError
array.fetch(4){ 42 } # => 42

hash.values_at(:b, :c) # => [2, 3]
hash.values_at(:b, :d) # => [2, nil]
array.values_at(1, 2) # => [2, 3]
array.values_at(1, 4) # => [2, nil]

hash.fetch_values(:b, :c) # => [2, 3]
hash.fetch_values(:b, :d) # => IndexError
hash.fetch_values(:b, :d){ 42 } # => [2, 42]
# missing
array.fetch_values(1, 2) # => [2, 3]
array.fetch_values(1, 4) # => IndexError
array.fetch_values(1, 4){ 42 } # => [2, 42]

Related issues 1 (0 open1 closed)

Related to Ruby master - Feature #10017: Add `Hash#fetch_values`Closedmatz (Yukihiro Matsumoto)Actions
Actions #1

Updated by mame (Yusuke Endoh) 4 months ago

Updated by matz (Yukihiro Matsumoto) 4 months ago

Looks like a good idea. Accepted.

Matz.

Actions #4

Updated by byroot (Jean Boussier) 4 months ago

  • Status changed from Open to Closed

Applied in changeset git|bc85c8d8529b58c5c649f418ca549569ba348caa.


Implement Array#fetch_values

[Feature #20702]

Works the same way than Hash#fetch_values for for array.

Actions

Also available in: Atom PDF

Like0
Like0Like1Like1Like0