Project

General

Profile

Feature #10829

Add to_proc method to the Array class

Added by BenMorganIO (Ben Morgan) about 4 years ago. Updated almost 4 years ago.

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

Description

In ruby, we've all seen this shortcut:

user.posts.map(&:title)

The expanded version is:

user.posts.map { |post| post.title }

Sometimes, however, that method might take arguments. This feature proposal is to allow the to_proc shortcut to be able to respond to the Array class. This would allow developers to be able to use the shortcut to be able to pass in arguments. This can currently be done by reopening the Array class and supplying it with a to_proc method:

class Array
  def to_proc
    proc { |receiver| receiver.send *self }
  end
end

This would allow this code to be able to run:

[1, 2, 3, 4, 5].map([:+, 3])
# => [4, 5, 6, 7, 8]

History

Updated by BenMorganIO (Ben Morgan) about 4 years ago

Update example code, there was a missing &:

[1, 2, 3, 4, 5].map(&[:+, 3])
# => [4, 5, 6, 7, 8]

Also available in: Atom PDF