Recently I've came up with this method:
module Enumerable
def transform
yield self
end
end
The purpose of method is similar to tap
method but with the ability to modify object.
For example with this method I can change order in an array in chain style:
array.do_something.transform{ |a| [a[3],a[0],a[1],a[2]] }.do_something_else
Instead of doing this:
a0,a1,a2,a3 = array.do_something
result = [a3, a0, a1, a2].do_something_else
There are also another conveniences when using this method but...
The method is very straightforward, so I guess somewhere should be the already built method with the same purpose.
Is there analogue for this ruby method?
You can do that with instance_eval
:
Evaluates (…) the given block, within the context of the receiver
Example:
%w(a b c d).instance_eval{|a| [a[3], a[0], a[1], a[2]] }
# => ["d", "a", "b", "c"]
or using self
:
%w(a b c d).instance_eval{ [self[3], self[0], self[1], self[2]] }
# => ["d", "a", "b", "c"]