What does @ stand for in the following Ruby code:
module TestRocket
extend Module.new { attr_accessor :out }
def _test(a, b); send((call rescue()) ? a : b); end
def +@; _show _test :_pass, :_fail end
def -@; _show _test :_fail, :_pass end
def ~@; _show _pend; end
def !@; _show _desc; end
def _show(r); (TestRocket.out || $>) << r; r end
def _pass; " OK\n"; end
def _fail; " FAIL @ #{source_location * ':'}\n"; end
def _pend; "PENDING '#{call}' @ #{source_location * ':'}\n"; end
def _desc; " FIRE '#{call}'!\n"; end
end
Proc.send :include, TestRocket
Then this is used as:
+-> { Die.new(2) }
--> { raise }
+-> { 2 + 2 == 4 }
How does @ turn into ‘->’ in the function name?
The method names for the four unary operators
+,-,~, and!are+@,-@,~@, and!@. So the funny looking method definitions:just define overloads for those four unary operators. Then TestRocket is patched into the Proc class using
Proc.send :include, TestRocket.This:
is simply a lambda definition and another way of writing
lambda { Die.new(2) }. Then, with TestRocket patched into Proc we can say this:and it will run this method:
as an instance method on that lambda.
Looks like a bit of an abuse of the unary operator overloading to “invent” something that looks like new
-->,~->, … operators.