Occasionally when writing Ruby I find myself wanting a pipe
method, similar to tap
but returning the result of calling the block with self
as a parameter, like this:
class Object
def pipe(&block)
block.call(self)
end
end
some_operation.pipe { |x| some_other_operation(x) }
..but so far I haven't managed to find out what it's called, if it exists. Does it exist?
If it doesn't, I know I could monkey-patch object to add it but, y'know, that's bad. Unless there's a brilliant, guaranteed to never clash (and descriptive and short) name I could use for it...
In Rubyists Already Use Monadic Patterns, Dave Fayram made a passing reference to using ||= to set a variable's value if its value were 'Nothing' ( false or nil in Ruby). The resulting Reddit quickly picked up on his definition (which was fixed later) and argued about ||= 's true meaning which isn't as obvious as many Rubyists think.
Ruby supports a rich set of operators, as you'd expect from a modern language. Most operators are actually method calls. For example, a + b is interpreted as a.+(b), where the + method in the object referred to by variable a is called with b as its argument.
Ruby Dot "." and Double Colon "::" Operators You call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.
Exponent AND assignment operator, performs exponential (power) calculation on operators and assign value to the left operand. Ruby also supports the parallel assignment of variables. This enables multiple variables to be initialized with a single line of Ruby code. For example − This may be more quickly declared using parallel assignment −
This abstraction doesn't exist in the core. I usually call it as
, it's short and declarative:
class Object
def as
yield(self)
end
end
"3".to_i.as { |x| x*x } #=> 9
Raganwald usually mentions that abstraction in his posts, he calls it into.
So, summing it up, some names: pipe
, as
, into
, peg
, thru
.
Ruby 2.5 introduced Object.yield_self which is exactly the pipe operator you're using: it receives a block, passes self as the first argument to it and returns the result of evaluating the block.
class Object
def yield_self(*args)
yield(self, *args)
end
end
Example usage:
"Hello".yield_self { |str| str + " World" }
# Returns "Hello World"
You can also read a little more about it in the following blog posts:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With