user1934428
user1934428

Reputation: 22217

Chaining methods in Ruby, and injecting a block into the chain

Consider the following Ruby expression:

y=x.a.b.c.d.e.f

Of course, x is an object and a to f are methods defined for a class which matches the return value of the previous method in the chain. Now say that I want to replace the invocation of method c by a custom block, i.e. I would like to achieve the effect of

temp=x.a.b
temp1=.... (calculate something based on the value of temp)
y=temp1.d.e.f

but with using method chaining.

It is of course trivial to define a suitable method to achieve this:

class Object

  def pass
    yield(self)
  end

end

which would allow me to write something like

y=x.a.b.pass {|the_b| .....}.d.e.f

Now to my question:

Given that Ruby already has a method for a similar problem (Object#tap), I wonder why it does not have a method similar to the Object#pass which I just explained. I suspect, that either

(a) Ruby already offers a feature like this, and I'm just to stupid to find it, or

(b) What I want to achieve would be considered bad programming style (but then, why?)

Is (a) or (b) correct, or did I miss something here?

Upvotes: 1

Views: 294

Answers (1)

sawa
sawa

Reputation: 168101

(a) Yes. Ruby already has that. It is called yield_self.

(b) No. It is not a bad style.

Upvotes: 3

Related Questions