Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby method chaining - `tap` with replacement [duplicate]

Possible Duplicate:
Is there a `pipe` equivalent in ruby?

I'm looking at the tap method in Ruby - but unfortunately the object returned from the passed block is not passed on. What method do I use to have the object passed on?

Here's what I'm trying to (unsuccessfully) do:

obj.tap{ |o| first_transform(o) }.tap{ |o| second_transform(o)}

This is, of course, equivalent to second_transform(first_transform(o)). I'm just asking how to do it the first way.

Doing this is trivial with lists:

list.map{ |item| first_transform(item) }.map{ |item| second_transform(item)}

Why isn't it as easy with objects?

like image 264
Sudhir Jonathan Avatar asked Nov 25 '25 18:11

Sudhir Jonathan


1 Answers

class Object
  def as
    yield self
  end
end

With this, you can do [1,2,3].as{|l| l << 4}.as{|l| l << 5}

like image 102
Selva Avatar answered Nov 27 '25 16:11

Selva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!