Project

General

Profile

Feature #15483

Updated by aycabta (aycabta .) almost 6 years ago

In [Feature #6284], #6284](is titled "Add composition for procs"), Matz said 

 > We need more discussion if we would add combination methods to the Symbol class. 

 Right, let's get started to discuss. 

 For your information, recent a few months I'm discussing this with @osyo . 

 ## This is a discussion of "design" 

 I understand that all features of this issue have both merits and demerits, but I guess that language design is most important. All features of this issue related to each other. 

 ## Abstract 

 At present, you can use `Proc#>>` or `Proc#<<` with `Symbol#to_proc`. 

 ```ruby 
 %w{72 101 108 108 111}.map(&(:to_i.to_proc >> :chr.to_proc)) 
 # => ["H", "e", "l", "l", "o"] 
 ``` 

 This is convenient but methods that take block can take a proc with `&` syntax sugar instead of `#to_proc` by right, like `[1, 2, 3].map(&:to_s)`. So `Symbol#to_proc` looks like too long for `Proc#>>` or `Proc#<<`. Therefore, you need new syntax sugar. 

 ## Receiver 

 ### `Symbol#>>` and `Symbol#<<` 

 `Symbol#>>` and `Symbol#<<` will be considered, but this means that `Symbol` is treated as `Proc` partially. The `[1, 2, 3].map(&:to_s)` treats `Symbol` as `Proc` partially too, but it's with pre-positioned `&`. 

 ```ruby 
 %w{72 101 108 108 111}.map(&(:to_i >> :chr.to_proc)) 
 # => ["H", "e", "l", "l", "o"] 
 ``` 

 I can't come up with other ideas for the `Symbol` receiver. 

 ### New `&:symbol_name` syntax sugar for `:symbol_name.to_proc` 

 ```ruby 
 %w{72 101 108 108 111}.map(&(&:to_i 111}.map(&:to_i >> :chr.to_proc))) :chr.to_proc)) 
 # => ["H", "e", "l", "l", "o"] 
 ``` 

 ## Argument 

 ### Calls `#to_proc` by `Proc#>>` or `Proc#<<` internally as a duck typing 

 ```ruby 
 %w{72 101 108 108 111}.map(&(:to_i.to_proc >> :chr)) 
 # => ["H", "e", "l", "l", "o"] 
 ``` 

 In this case, `Proc#>>`(`:to_i.to_proc >>`) calls `Symbol#to_proc`(for `:chr`) inside. 

 This is useful to use with `Hash#to_proc`: 

 ```ruby 
 h = { Alice: 30, Bob: 60, Cris: 90 } 
 %w{Alice Bob Cris}.map(&(:to_sym.to_proc >> h)) 
 # => [30, 60, 90] 
 ``` 

 ### `Proc#>>` and `Proc#<<` take block as an argument 

 ```ruby 
 %w{72 101 108 108 111}.map(&(:to_i.to_proc >> &:chr)) 
 ``` 

 ## Combination of receiver and argument 

 `Symbol#>>` and calling `#to_proc` internally: 

 ```ruby 
 %w{72 101 108 108 111}.map(&(:to_i >> :chr)) 
 # => ["H", "e", "l", "l", "o"] 
 ``` 

 `&:symbol_name` syntax sugar for `:symbol_name.to_proc` and `Symbol#>>` and taking block: 

 ```ruby 
 %w{72 101 108 108 111}.map(&(&:to_i >> &:chr)) 
 # => ["H", "e", "l", "l", "o"] 
 ``` 

Back