Feature #16113
openPartial application
Description
Preface: One of the main "microstructures" of the code we use is chaining methods-with-blocks; and we really love to keep those blocks DRY when they are simple. Currently, for DRY-ing up simple blocks, we have:
foo(&:symbol)
-
foo(&some.method(:name))
(as of 2.7,foo(&some.:name)
) - Currently disputed "nameless block args":
foo { something(@1) }
orfoo { something(@) }
orfoo { something(it) }
Proposal: I argue that short and easy-to-remember partial application of blocks and methods can make methods-with-blocks much more pleasant and consistent to write, and continue softly shifting Ruby towards "functional" (while staying true to language's spirit).
In order to achieve this, I propose method {Symbol,Method,Proc}#w
(from with
), which will produce Proc
with last arguments bound.
Example of usability:
# No-shortcuts: fetch something and parse as JSON:
fetch(urls).map { |body| JSON.parse(body) }
# Could be already (2.7+) shortened to:
fetch(urls).map(&JSON.:parse)
# But if you have this:
fetch(urls).map { |body| JSON.parse(body, symbolize_names: true) }
# How to shorten it, to don't repeat body?
# "Nameless block args" answer:
fetch(urls).map { JSON.parse(@1, symbolize_names: true) }
# Partial application answer:
fetch(urls).map(&JSON.:parse.w(symbolize_names: true))
I believe that the latter (while can be easily met with usual "hard to understand for a complete novice") provides the added value of producing proper "functional object", that can be stored in variables and constants, and generally lead to new approaches to writing Ruby code.
Another example:
(6..11).map(&:**.w(2)).map(&:clamp.w(20, 50))
# => [36, 49, 50, 50, 50, 50]
Reference implementation:
class Symbol
def w(*args)
proc { |receiver, *rest| receiver.send(self, *rest, *args) }
end
end
class Method
def w(*args)
proc { |receiver, *rest| self.call(receiver, *rest, *args) }
end
end
class Proc
def w(*args)
prc = self
proc { |*rest| prc.call(*rest, *args) }
end
end