[#97536] [Ruby master Bug#16694] JIT vs hardened GCC with PCH — v.ondruch@...
Issue #16694 has been reported by vo.x (Vit Ondruch).
11 messages
2020/03/18
[ruby-core:97595] [Ruby master Feature#16739] Allow Hash#keys and Hash#values to accept a block for filtering output
From:
mame@...
Date:
2020-03-25 15:14:31 UTC
List:
ruby-core #97595
Issue #16739 has been updated by mame (Yusuke Endoh).
I doubt if it is obvious. See the following code. I believe that many people expect `.map`.
```ruby
hash.keys {|k| k.to_s }
```
If you want to avoid an intermediate array, you may want to use `.each_key` or `.filter_map`.
```ruby
hash.each_key.select {|k| k.nil? || k.even? }
hash.filter_map {|k, v| k if valid_key?(k) && valid_value?(v) }
```
Personally I like the following explicit code, though.
```ruby
keys = []
hash.each do |k, v|
keys << k if valid_key?(k) && valid_value?(v)
end
```
----------------------------------------
Feature #16739: Allow Hash#keys and Hash#values to accept a block for filtering output
https://bugs.ruby-lang.org/issues/16739#change-84779
* Author: jacobevelyn (Jacob Evelyn)
* Status: Open
* Priority: Normal
----------------------------------------
I often see code like the following:
``` ruby
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:
```ruby
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:
1. Does not break any existing code (since `Hash#keys` and `Hash#values` do not currently accept blocks).
2. Is very readable—it's obvious what it does at a glance.
3. Is more efficient than current alternatives.
4. Is more concise than current alternatives.
5. 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).
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>