Skip to content

Instantly share code, notes, and snippets.

@felixrabe
Created February 29, 2012 14:38
Show Gist options
  • Save felixrabe/1941252 to your computer and use it in GitHub Desktop.
Save felixrabe/1941252 to your computer and use it in GitHub Desktop.
truth.rb
#!/usr/bin/env ruby
class Object
def > other # implication operator: false > true == true
if self == true or self == false
!self or other
else
super
end
end
end
class FalseClass ; def to_01 ; "0" ; end ; end
class TrueClass ; def to_01 ; "1" ; end ; end
class TruthTable
attr_reader :map, :results
def initialize &block
raise ArgumentError, "block expected", caller unless block
raise ArgumentError, "block should not take arguments" if block.arity > 0
@counter = 0
@map = []
@results = []
until @counter == 2 ** @map.size
@results << instance_eval(&block)
@counter += 1
end
end
def method_missing name
index = @map.index name
if index
mask = 2 ** index
@counter & mask != 0
else
@map << name
false
end
end
end
def truth_table &block
truth_table = TruthTable.new &block
map = truth_table.map
results = truth_table.results
n = map.size
puts map.join " "
f = "%0#{n}b"
lines = []
for i in 0...2**n
a_s = (f % i).reverse
a_a = a_s.split("").map{|c| c != "0"}
inputs = map.map(&:size).each_with_index.map{|s,i| "%-#{s}s" % a_a[i].to_01}.join " "
output = results[i].to_01
lines << "#{inputs} => #{output}"
end
puts lines.sort
end
alias tt truth_table
@felixrabe
Copy link
Author

Example usage: ruby -r ./truth.rb -e 'tt { a and not b }'

@felixrabe
Copy link
Author

Implication: ruby -r ./truth.rb -e 'tt { this > that }'

@thaiviet1994
Copy link

Creating a “truth table” is not hard, you can use an useful tool (CKod, at http://ckod.sourceforge.net/_/) to make a “truth table”.

  1. CKod homepage: http://ckod.sourceforge.net/
  2. CKod online: http://ckod.sourceforge.net/_/
  3. CKod forum: http://ckod.sourceforge.net/~/

Good luck to you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment