Project

General

Profile

Actions

Feature #20657

closed

Allow Enumerable#map(&:method) and #each accept additional parameters for method

Added by ukolovda (Dmitry Ukolov) 4 months ago. Updated 4 months ago.

Status:
Feedback
Assignee:
-
Target version:
-
[ruby-core:118737]

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) 4 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) 4 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) 4 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) 4 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.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0