« Back to Index

Ruby Data Structures: Set

View original Gist on GitHub

Ruby Set.md

Set, included in the stdlib, is an un-ordered collection of elements with no duplicates. However you’ll find that Set’s most useful feature is that its #include? method is much faster than Array’s. In fact Set#include? will always take the same amount of time, regardless of how many elements it contains, whereas Array#include? takes longer the more elements in the array.

Sets do take longer to build than Arrays, so work best when they can be created just once and assigned to a constant, or instance variable of a long lived object.

require "set"

TEMP_EMAIL_PROVIDERS = Set["temp-email.tld", "throwaway-mail.tld", ...]

def temporary_email?(address)
  TEMP_EMAIL_PROVIDERS.include?(address.split("@").last.downcase)
end