If I want to perform a map operation using a function…
def somefunc(x)
… perform some operation on x …
… and return a value …
end
I have to do this:
l = [1,2,3].map { |x| somefunc x }
Why shouldn’t I be able to do this:
l = [1,2,3].map somefunc
It’s just not how Ruby works, for a number of reasons. If ‘somefunc’ were
truly a function, then it would seem strange not to be able to do that.
But ‘somefunc’ is a method, and as such it is bound up in the state of
some object.
Ruby will not sacrifice the purity of its OO concept for a bit of extra
convenience. (It already has convenience in spades.)
The ‘extensions’ project on RubyForge has a couple of shortcuts aimed at
map, but not in the (function-oriented) way you want.
require ‘extensions’
a = [1, -2, 3]
a.mapf :abs # short for a.map { |n| n.abs }
a.map &:abs # ditto
The second example is a bit ugly and opaque, but it can be applied to any
method, whereas the first is obviously limited to map/collect.
An alternative for your code is
a.map method(:somefunc)
Ultimately, you have to look at your suggested code
a.map somefunc
and realise that ‘somefunc’ must be either a local variable or a method
invocation. Treating it as a method object (like method(:somefunc)) would
mean that all method invocations would require parentheses, which would be
unpopular.