3 ms·
PHP: $result = $arr |> fn($x) => array_column($x, 'tags') // Gets an array of arrays |> fn($x) => array_merge(...$x) // F
by Mystery-Machine 1y ago
PHP:
$result = $arr
|> fn($x) => array_column($x, 'tags') // Gets an array of arrays
|> fn($x) => array_merge(...$x) // Flatten into one big array
|> array_unique(...) // Remove duplicates
|> array_values(...) // Reindex the array.
; // <- wtf
Ruby:
result = arr.uniq.flatten.map(&:tags)
I understand this is not pipe operator, but just look at that character difference across these two languages.
// <- wtf
This comment was my $0.02.
- moebrowne 1y agoThe trailing semi-colon on a new line helps prevent Git conflicts and gives cleaner diffs. It's the same reason PHP allows trailing commas in all lists.
- Alifatisk 1y agoCan'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.
- daneel_w 1y agoPutting the delimiter on a line of its own is a syntactical trick that helps bringing small additions down to a neater 1-line diff instead of a 2-line diff. You've probably run into it many times before in other contexts without thinking of it. Arrays/hashes, quoted multi-line strings etc.
- hu3 1y agoPeople use Laravel Collections or similar Symfony array wrapper to achieve chaining. Most PHP code I see look like your Ruby example.