I often find myself writing ruby code that looks like this:
b = f1(a)
c = f2(b)
d = f3(c)
...
Is there a way to chain f1
, f2
, f3
together regardless of the types of a, b, and c? For examplesomething like
a.send_to(&:f1)
.sent_to(&:f2)
.sent_to(&:f3)
It doesn't need to be exactly that, but I like the code that can be read, in order, as "start with a
, now apply f1
, then apply f2
, ..."
It occurs to me that all I'm really asking for here is a way to use map
on a single object rather than a list. E.g. I could do this:
[a].map(&:f1)
.map(&:f2)
.map(&:f3)
.first
The following (sort of) works, though monkey-patching Object
seems like a bad idea:
class Object
def send_to(&block)
block.call(self)
end
end
I say "(sort of) works" because
1.send_to{|x| x+1}
#=> 2
but
def add_1(x); x+1; end
1.send_to(&:add_1)
#=> NoMethodError: private method `add_1' called for 0:Fixnum
Note: This question asks something similar, but the proposal is to define a method on the particular class of each object.