Skip to content

Instantly share code, notes, and snippets.

@stevecj
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevecj/9742269 to your computer and use it in GitHub Desktop.
Save stevecj/9742269 to your computer and use it in GitHub Desktop.
Stoopid Ruby trick <g>
class Trinary
class << self
def ~ ; ~new ; end
def -@ ; -new ; end
def +@ ; +new ; end
end
def initialize(digits=[])
@digits = digits
end
def ~ ; self.class.new(@digits.dup.unshift(0)) ; end
def -@ ; self.class.new(@digits.dup.unshift(1)) ; end
def +@ ; self.class.new(@digits.dup.unshift(2)) ; end
def to_i
@digits.inject{ |v,d| v * 3 + d }
end
end
t = ~Trinary
puts t.to_i
# => 0
t = -Trinary
puts t.to_i
# # => 1
t = +Trinary
puts t.to_i
# # => 2
t = -~++Trinary
puts t.to_i
# # => 35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment