Issue #5663 has been updated by Alexey Muranov.


Rodrigo Rosenfeld Rosas wrote:
> Em 25-11-2011 01:00, Nobuyoshi Nakada escreveu:
>  > Issue #5663 has been updated by Nobuyoshi Nakada.
>  >
>  >
>  > Rodrigo Rosenfeld Rosas wrote:
>  >> Nobuyoshi, wouldn't&:even? be equivalent to :even?.to_proc? I just find that the example reads better this way ;)
>  > They are different.
>  > &expr calls #to_proc method on the result of expr, to achieve a Proc object.
>  >
>  >> (1..10).grep(&:even?){|i|i+1}
>  > It's a syntax error.
>  
>  Wow! Thanks! This is unexpected to me. I didn't know about the difference.
>  
>  Anyway, I still didn't understand why (1..10).grep(&:even?) works, but 
>  (1..10).grep(&:even?){|i| i+1} not.
>  
>  Actually, I didn't understand your explanation. You said that &expr 
>  calls #to_proc on the result of expr. What is the expr on each example? 
>  Is there any place I could further read about those differences?
>  
>  Thank you, Rodrigo.

I am not a specialist, but it seems that you can only use ampersand in a `def` with the *last* parameter, and in such case this last parameter becomes the name of a block passed to the method.  Similarly, when you call a method, you can either supply a block, or pass a proc as a block by adding it as the last argument prefixed with ampersand, but not both, because you cannot pass two blocks to a method (but you can pass multiple procs).  So basically only one ampersand is allowed, and only if you do not supply a block.

Here is a link about blocks a procs, but it does not explain this detail:
http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
----------------------------------------
Feature #5663: Combined map/select method
http://redmine.ruby-lang.org/issues/5663

Author: Yehuda Katz
Status: Open
Priority: Normal
Assignee: 
Category: lib
Target version: 2.0.0


It is pretty common to want to map over an Enumerable, but only include the elements that match a particular filter. A common idiom is:

enum.map { |i| i + 1 if i.even? }.compact

It is of course also possible to do this with two calls:

enum.select { |i| i.even? }.map { |i| i + 1 }

Both cases are clumsy and require two iterations through the loop. I'd like to propose a combined method:

enum.map_select { |i| i + 1 if i.even? }

The only caveat is that it would be impossible to intentionally return nil here; suggestions welcome. The naming is also a strawman; feel free to propose something better.


-- 
http://redmine.ruby-lang.org