Skip to content

Instantly share code, notes, and snippets.

@stevecj stevecj/trinary.rb
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.