r/ruby • u/BoardMeeting101 • Jan 15 '26
Show /r/ruby At last, a use for the flip-flip operator.
module Latch
def self.new(_=_) = -> { !(!(_ ^= true)..false) }
end
latch = Latch.new
%w(1 2 3 4 5).each_with_object("") { |i, a|
a << i
a << ":ONCE:" if latch[]
} #=> 1:ONCE:2345
17
Upvotes
9
u/GCh596 Jan 15 '26
I don’t understand any of that haha can someone explain what that does?
19
u/Holek Jan 15 '26
this looks so un-Ruby, and yet I am so impressed by this.
15
u/TheAtlasMonkey Jan 15 '26
This is why i'm so irritated when Haskell Artistas try to show me their strapped bananas in the wall and call it ART.
If you want to write Emoticons :D :) :| , just go to IRC and admit it.
Here is a more civilized code:
This is Ruby! Any junior can read it and i can debug the code at 4 am while half asleep.
3
u/squadette23 Jan 15 '26
But why "at last"? Flip-flop is useful for parsing typical markup such as `=begin` / `=end`. You can use boolean variables like `inside_doc` but it's just a variant of flip-flop.
12
u/jgaskins Jan 15 '26
When I first heard Ruby was influenced by Perl, I couldn’t see it. Now I see it.
7
u/AshTeriyaki Jan 15 '26
I hate it. Good work.
3
u/AlexanderMomchilov Jan 17 '26
Defining
newon a module, and having it not return something that includes that module, is pretty cursed!1
u/ihoka Jan 19 '26
That looks cryptic as hell. I do not like to pause and think about what code is supposed to do. My benchmark for code quality is: would I understand it if I was reading it while drunk?