Linked Questions

Popular Questions

ruby method chaining for arbitrary objects, classes

Asked by At

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


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:


The following (sort of) works, though monkey-patching Object seems like a bad idea:

class Object
  def send_to(&block)

I say "(sort of) works" because

1.send_to{|x| x+1}
#=> 2


def add_1(x); x+1; end  
#=> 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.

Related Questions