Skip to content

Instantly share code, notes, and snippets.

@asaaki
Created July 21, 2011 17:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asaaki/1097706 to your computer and use it in GitHub Desktop.
Save asaaki/1097706 to your computer and use it in GitHub Desktop.
Ruby Unary operator overloading and it's oddities
### 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
@janlelis
Copy link

f.-@0#:D

@asaaki
Copy link
Author

asaaki commented Jul 22, 2011

Thanx. Very unreadable code then. :o)

(Damn, not to see the obvious.)

@janlelis
Copy link

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

@asaaki
Copy link
Author

asaaki commented Jul 22, 2011

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