I was goofing around in a pry REPL and found some very interesting behavior: the tilde method.
It appears Ruby syntax has a built-in literal unary operator, ~
, just sitting around.
This means ~Object.new
sends the message ~
to an instance of Object
:
class Object
def ~
puts 'what are you doing, ruby?'
end
end
~Object.new #=> what are you doing, ruby?
This seems really cool, but mysterious. Is Matz essentially trying to give us our own customizable unary operator?
The only reference I can find to this in the rubydocs is in the operator precedence notes, where it's ranked as the number one highest precedence operator, alongside !
and unary +
This makes sense for unary operators. (For interesting errata about the next two levels of precedence, **
then unary -
, check out this question.) Aside from that, no mention of this utility.
The two notable references to this operator I can find by searching, amidst the ~=,
!~, and
~>` questions, are this and this. They both note its usefulness, oddity, and obscurity without going into its history.
After I was about to write off ~
as a cool way to provide custom unary operator behavior for your objects, I found a place where its actually used in ruby--fixnum (integers).
~2
returns -3
. ~-1
returns 1
. So it negates an integer and subtracts one... for some reason?
Can anyone enlighten me as purpose of the tilde operator's unique and unexpected behavior in ruby at large?