Project

General

Profile

Actions

Feature #12115

open

Add Symbol#call to allow to_proc shorthand with arguments

Added by felixbuenemann (Felix Bünemann) over 5 years ago. Updated almost 3 years ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:74011]

Description

I am a great fan of the Symbol#to_proc shorthand when mapping or reducing collections:

[1,2,16].map(&:to_s)
=> ["1", "2", "16"]
[1,2,16].reduce(&:*)
=> 32

I often wish it would be possible to pass an argument to the method when doing this, which currently requires a block and is more verbose:

[1,2,16].map { |n| n.to_s(16) }
=> ["1", "2", "10"]
# active_support example
{id: 1, parent_id: nil}.as_json.transform_keys { |k| k.camelize :lower }.to_json
=> '{"id":1,"parentId":null}'

It would be much shorter, if ruby allowed this:

[1,2,16].map(&:to_s.(16))
=> ["1", "2", "10"]
# active_support example
{id: 1, parent_id: nil}.as_json.transform_keys(&:camelize.(:lower)).to_json
=> '{"id":1,"parentId":null}'

This can be implemented easily, by adding the Symbol#call method:

class Symbol
  def call(*args, &block)
    ->(caller, *rest) { caller.send(self, *rest, *args, &block) }
  end
end

Source: stackoverflow: Can you supply arguments to the map(&:method) syntax in Ruby?

I think this is a rather common use case, so I propose to add Symbol#call to the Ruby standard library.


Related issues

Related to Ruby master - Feature #4146: Improvement of Symbol and ProcRejectednobu (Nobuyoshi Nakada)Actions
Has duplicate Ruby master - Feature #15301: Symbol#call, returning method bound with argumentsClosedActions
Actions

Also available in: Atom PDF