Sets
An array is a list: it has an order, and the same thing may turn up in it again and again. Often, though, all you care about is what is there – the guests at a party, the stickers in your album, the letters of a word. That is a set, and Ruby has it built in: Set. (Older Rubies needed require "set" first – the line does no harm, so it stays.) In a set everything is in only once – duplicates simply vanish:
require "set"
guests = Set["Chunky", "Kaz", "Chunky", "Isi", "Kaz"]
p guests
guests.sizeRuby shows a set as Set[…]. Chunky and Kaz were invited twice – the set counts them once. You add with << or add; adding what is already in changes nothing. include? asks whether something is in – and for a set that is fast, however big it gets: a set works like a hash with only keys (lesson 11), so it looks the thing up instead of searching the whole list:
album = Set.new
album << "fox" << "owl"
album.add("fox") # already in: nothing happens
p album.include?("owl")
album.sizeadd? with a question mark adds too, but it also tells you whether that worked: if the element was in already, it gives nil. That way you notice the first repeat while you are still collecting – here the first number rolled a second time. With ⏯ you can watch seen grow:
rolls = [4, 2, 6, 2, 5, 4]
seen = Set.new
rolls.each do |roll|
unless seen.add?(roll)
puts "#{roll} comes up for the second time!"
break
end
endSets show their real strength when you compare two of them. What do Chunky and Kaz like for breakfast? & is what both like, | what at least one of them likes, - what only Chunky likes, and ^ what exactly one of the two likes – think of two circles that overlap:
chunky = Set["bacon", "egg", "toast", "jam"]
kaz = Set["egg", "fish", "toast", "honey"]
p chunky & kaz # both
p chunky | kaz # at least one of them
p chunky - kaz # only Chunky
chunky ^ kaz # exactly one of themArrays know &, | and - too, by the way – but with a set it is clear that order and duplicates don't matter. Then there are questions about two sets as a whole: is one of them completely inside the other (subset?), does one contain the other (superset?), do the two have nothing in common (disjoint?)? Is there enough in the pantry for pancakes, and is there enough for waffles?
pantry = Set["flour", "egg", "milk", "sugar"]
pancakes = Set["flour", "egg", "milk"]
waffles = Set["flour", "egg", "butter"]
p pancakes.subset?(pantry)
p pantry.superset?(pancakes) # the same, seen from the pantry
p waffles.subset?(pantry)
p waffles - pantry # still to buy
pantry.disjoint?(Set["fish", "rice"])Pancakes yes, waffles only with butter from the shop. Last of all: to_set turns any list into a set. Two sets are equal when they hold the same things – in whatever order, unlike arrays. So when do you take a set, and when is an array with uniq enough? uniq will do when you want the duplicates out of a list once, and it keeps the order. A set is the right tool when you keep adding and asking include?, or when you compare groups with &, | and -:
letters = "banana".chars
p letters.uniq # an array: the order stays
p letters.to_set # a set
p Set[1, 2, 3] == Set[3, 2, 1]
[1, 2, 3] == [3, 2, 1]A rule of thumb: an array when order or repeats matter (a queue, a high score list, a shopping list with three eggs), a set when all that matters is “in or not?” (who is coming, what we have, what is still missing).
both – the stickers both of them have; for_kaz – the ones Chunky has and Kaz is still missing. And count in kinds how many different stickers the two have together.chunky_stickers = %w[fox owl bear fox frog owl]
kaz_stickers = %w[owl hedgehog frog frog deer]
# both = ... # the stickers both of them have, as a set
# for_kaz = ... # Chunky's stickers Kaz is missing, as a set
# kinds = ... # how many different stickers they have together
pangram whether sentence is one (true or false), and in missing which letters other lacks – as one string, sorted from a to z. Capitals count as small letters, and ("a".."z").to_set is the whole alphabet as a set.sentence = "The quick brown fox jumps over the lazy dog"
other = "Chunky the fox jumps over the lazy dog"
# pangram = ... # true when sentence has every letter from a to z
# missing = ... # the letters other lacks, as one string, a to z