The letter A styled as Alchemists logo. lchemists
Published October 31, 2019 Updated February 16, 2020

Ruby Truth Tables

Demonstrates how to build and use truth tables.

Transcript

# Hello and welcome to the Alchemists Screencasts!
# Today, we'll look at using Truth Tables in Ruby.
# Let's say we have three boolean values and want to know all possible lookup combinations:

#  value 1  | value 2 | value 3  | combination index
# ----------+---------+----------+-------------------
#     1     |    1    |    1     |         0
#     1     |    1    |    0     |         1
#     1     |    0    |    1     |         2
#     1     |    0    |    0     |         3
#     0     |    1    |    1     |         4
#     0     |    1    |    0     |         5
#     0     |    0    |    1     |         6
#     0     |    0    |    0     |         7

irb

table = [true, false].repeated_permutation(3).to_a

# If it helps, here is what this looks like via Awesome Print:

ap table

# With our truth table in hand, we can ask the table for the index of any combination:

table.index [true, true, true]
table.index [true, false, true]
table.index [false, false, false]

# Moving this logic to a method, we can provide some syntatic sugar.

def truth_table_index(*combinations)
  [true, false].repeated_permutation(3)
               .to_a
               .then { |table| table.index combinations }
end

# There is no longer a need to build new arrays like before.
# We can pass in the boolean combination values instead.

truth_table_index true, true, true
truth_table_index true, false, true
truth_table_index false, false, false
exit

# Note that bit shifting would be more performant.
# Yet, it is good to know we can use arrays for representing truth tables.

# Enjoy!
# https://alchemists.io
# ☿ 🜔 🜍 🜂 🜃 🜁 🜄