Created
July 21, 2011 17:30
-
-
Save asaaki/1097706 to your computer and use it in GitHub Desktop.
Ruby Unary operator overloading and it's oddities
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### The 4 unaries are: + - ~ ! | |
### If you really found more, tell me ;o) | |
class Foo | |
def +@ | |
puts "unary plus (in front of object) / without param" | |
end | |
def -@(a=42) | |
# please tell me, how could I pass an argument to an unary operation? | |
# but it's possible to define arguments, curious ... | |
puts "unary minus (in front of object) / with param: #{a}" | |
end | |
def -(nr) | |
puts "binary minus! (behind object) / with param: #{nr}" | |
end | |
end | |
f = Foo.new | |
+f #=> unary plus (in front of object) / without param | |
-f #=> unary minus (in front of object) / with param: 42 | |
f-23 #=> binary minus! (behind object) / with param: 23 |
Thanx. Very unreadable code then. :o)
(Damn, not to see the obvious.)
Yep, it's possible, but nobody uses such things ;). (Another example would be defining multiple args for <<
)
Btw1: Overloading unary operators for symbols: http://rubyzucker.info/#unary
Btw2: Superators http://www.rubyinside.com/superators-add-new-operators-to-ruby-592.html xD
BTW: this gist was only a showcase for unary discussion on https://gist.github.com/1075747
The superators sound interesting, but not really functional (the gem is outdated / a trouble making issue was mentioned).
Would be really nice, if there is a possibility of defining own unary operators in Ruby.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
f.-@0#:D