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?
By convention, method names begin with a lowercase letter. (Method names can begin with a capital letter, but that makes them look like constants.) When a method name is longer than one word, the usual convention is to separate the words with underscores like_this rather than using mixed case likeThis .
Ruby Dot "." and Double Colon "::" Operators The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module.
Functions in Ruby are created using the def keyword (short for define). Functions that exist in an object are typically called methods. Functions and methods are the same, except one belongs to an object. Objects are created from classes using the .new method.
Bang or exclamation mark means that you are making a permanent saved change in your code. If you use for example Ruby's method for global substitution gsub! the substitution you make is permanent.
The method names for the four unary operators +
, -
, ~
, and !
are +@
, -@
, ~@
, and !@
. So the funny looking method definitions:
def +@; _show _test :_pass, :_fail end
def -@; _show _test :_fail, :_pass end
def ~@; _show _pend; end
def !@; _show _desc; end
just define overloads for those four unary operators. Then TestRocket is patched into the Proc class using Proc.send :include, TestRocket
.
This:
-> { Die.new(2) }
is simply a lambda definition and another way of writing lambda { Die.new(2) }
. Then, with TestRocket patched into Proc we can say this:
+-> { Die.new(2) }
# + lambda { Die.new(2) }
and it will run this method:
def +@; _show _test :_pass, :_fail end
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.
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