4 ms·
Can't the pipe operator be easily mimicked in Ruby thanks to its flexibility? I'm thinking of something like this: class Object def |>(fn) f
by Alifatisk 1y ago
Can't the pipe operator be easily mimicked in Ruby thanks to its flexibility?
I'm thinking of something like this:
class Object
def |>(fn)
fn.call(self)
end
end
which then can be in the following way:
result = arr
|> ->(a) { a.uniq }
|> ->(a) { a.flatten }
|> ->(a) { a.map(&:tags) }
Or if we just created an alias for then #then method:
class Object
alias_method :|>, :then
end
then it can be used like in this way:
arr
|> :uniq.to_proc
|> :flatten.to_proc
|> ->(a) { a.map(&:tags) }
- rafark 1y agoThe great thing about this pipe operator is that it accepts any callable expression. I’m writing a library to make these array and string functions more expressive. For example, in php 8.5 you’ll be able to do: [1,1,2,3,2] |> unique And then define “unique” as a constant with a callback assigned to it, roughly like: const unique = static fn(array $array) : array => array_unique($array); Much better.