Set Theory Basics using Arrays in Ruby

While studying title case and a kata at codewars.com, I stumbled onto the concept of Sets in Ruby. Sets are an object type in Ruby, just like Array or Hash, and are also a type of collection. Set implementation in Ruby is very much the mathematical operations encountered in Set Theory.

Quick fact: set is the most defined word in the dictionary.

Arrays are very similar and thus similar operations can be used to ascertain information quickly such as intersecting and non-intersecting elements. Here are some quick examples I noticed:


> a = %w(1 2 3 4 5)
=> ["1", "2", "3", "4", "5"]
> b = %w(2 4 6 8)
=> ["2", "4", "6", "8"]

# Subtraction (find the elements non-intersecting of A compared to B aka Left-Join)
> a-b
=> ["1", "3", "5"]

> b-a
=> ["6", "8"]

# Addition (total all elements both intersecting and non-intersecting (includes duplicates!) aka Full Outer Join)
> a+b
=> ["1", "2", "3", "4", "5", "2", "4", "6", "8"]

# Intersection (find elements in common aka Inner Join)
> a & b
=> ["2", "4"]

# Union (total all elements both intersecting and non-intersecting (excluding duplicates!) aka Full Outer Join modified)
a | b
=> ["1", "2", "3", "4", "5", "6", "8"]

Also check out Coding Horror’s blog, excellent overview of SQL joins with nice pics and explanations:

http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/

Structured Query Language aka SQL joins are quite analogous. See this pic below:

 

SQL Joins

Advertisements

2 comments

    • Joseph Tingsanchali

      Short story long: In relation to Russell’s paradox, we cannot conclude that a set (of all sets) contains itself because we haven’t formulated a definite and precise definition of a “set.” Modern set theory axioms provide a flexible way to prevent such a paradox and thus we forbid such a set if it contains itself. So the answer is no, not in the context of how we would consider a set to be a set of equivalent definition.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s