[ruby-core:95822] [Ruby master Feature#16341] Proposal: Set#to_proc and Hash#to_proc
From:
shannonskipper@...
Date:
2019-11-12 19:44:51 UTC
List:
ruby-core #95822
Issue #16341 has been updated by shan (Shannon Skipper).
Nondv (Dmitry Non) wrote:
> Speaking of hashes, they could implement implicit proc conversion as well:
>
> ```ruby
> class Hash
> def to_proc
> ->(key) { self[key] }
> end
> end
>
> dogs = ['Lucky', 'Tramp', 'Lady']
> favourite_food = { 'Lucky' => 'salmon', 'Tramp' => 'pasta', 'Lady' => 'pasta' }
>
> food_to_order = dogs.map(&favourite_food)
> ```
This already works! Hash#to_proc was added in Ruby 2.3. [ruby-core:11653](https://bugs.ruby-lang.org/issues/11653)
I like the idea of Set#to_proc.
----------------------------------------
Feature #16341: Proposal: Set#to_proc and Hash#to_proc
https://bugs.ruby-lang.org/issues/16341#change-82651
* Author: Nondv (Dmitry Non)
* Status: Open
* Priority: Normal
* Assignee:
* Target version:
----------------------------------------
``` ruby
class Set
def to_proc
-> (x) { include?(x) } # or method(:include?).to_proc
end
end
```
Usage:
```ruby
require 'set'
banned_numbers = Set[0, 5, 7, 9]
(1..10).reject(&banned_numbers) # ===> [1, 2, 3, 4, 6, 8, 10]
```
**UPD**
also for hash:
```ruby
class Hash
def to_proc
->(key) { self[key] }
end
end
dogs = ['Lucky', 'Tramp', 'Lady']
favourite_food = { 'Lucky' => 'salmon', 'Tramp' => 'pasta', 'Lady' => 'pasta' }
food_to_order = dogs.map(&favourite_food)
```
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>