Actions
Feature #16739
openAllow Hash#keys and Hash#values to accept a block for filtering output
Status:
Open
Assignee:
-
Target version:
-
Description
I often see code like the following:
hash.select { |_, v| v == :some_value }.keys
hash.keys.select { |k| k.nil? || k.even? }
hash.select { |k, v| valid_key?(k) && valid_value?(v) }.values
Each of these code snippets must allocate an intermediate data structure. I propose allowing Hash#keys
and Hash#values
to accept optional block parameters that take both key and value. For example, the above code could be rewritten as:
hash.keys { |_, v| v == :some_value }
hash.keys { |k, _| k.nil? || k.even? }
hash.values { |k, v| valid_key?(k) && valid_value?(v) }
This behavior:
- Does not break any existing code (since
Hash#keys
andHash#values
do not currently accept blocks). - Is very readable—it's obvious what it does at a glance.
- Is more efficient than current alternatives.
- Is more concise than current alternatives.
- Is flexible and useful in a variety of scenarios, because the block has access to both key and value (unlike the behavior proposed in #14788).
Actions
Like0
Like0Like0Like0Like0Like0Like0