Feature #20657
closedAllow Enumerable#map(&:method) and #each accept additional parameters for method
Description
I can use #map
(or #each
) with short method name, for example:
a = ["a1", "b1", "c1"]
b = a.map(&:length)
# or
a.each(&:some_method)
But with additional arguments I must use yield:
c = a.map { |item| item.ljust(10) }
# or
a.each { |item| item.some_method(arg1, arg2) }
Direct sending allow make the code more simple:
c = a.map(&:ljust, 10) # Now give syntax error, unexpected ',', expecting ')'
# or
a.each(&:some_method, arg1, arg2) # Now give syntax error, unexpected ',', expecting ')'
Updated by bkuhlmann (Brooke Kuhlmann) 3 months ago
Method Parameters And Arguments are already complex (powerful but complex). Historically, the block parameter has always been at the last position and optional by default. This would introduce new method signature complexity if a block was allowed to appear before positional and/or keyword arguments.
What you might want instead, is a refinement to Symbol#call
as provided by my Refinements gem. Example:
using Refinements::Symbol
a.map(&:ljust.call(10))
# [
# "a1 ",
# "b1 ",
# "c1 "
# ]
This would allow you to achieve what you asking for -- with tad more syntax than what you describe -- without making a drastic change to the language. Anyway, food for thought.
Updated by matz (Yukihiro Matsumoto) 3 months ago
As @bkuhlmann (Brooke Kuhlmann) mentioned, there's room for the language enhancement here to provide arguments to the method for a block. But not this way.
Because the arguments belong to the method, not the method call (each or map in the example).
Matz.
Updated by ukolovda (Dmitry Ukolov) 3 months ago
Oo, the ampersand is not language syntax, as I think before, but simple operator, converting Symbol to Proc. It is fine trix, but cannot accept additional arguments.
I'm disappointed.
Thank you for the clarification.
Updated by nobu (Nobuyoshi Nakada) 3 months ago
- Status changed from Open to Feedback
ukolovda (Dmitry Ukolov) wrote in #note-3:
Oo, the ampersand is not language syntax, as I think before, but simple operator, converting Symbol to Proc. It is fine trix, but cannot accept additional arguments.
You mean ampersand+colon(&:
)?
"Additional parameters" feature has been requested many times and in many ways (including the same as your proposal) already, but no acceptable solution.
Instead, numbered parameters (_1
, _2
, ...) and it
parameter have been introduced.