I like to read code. Often I take notes and it's a shame that I did never share them. But it's never to late to start.
So here are some notes on Ruby's set.rb. I hope you in turn share an interesting read with the world ;)
def initialize(enum = nil, &block)
@hash ||= Hash.new
enum.nil? and return
if block
do_with_enum(enum) { |o| add(block[o]) }
else
merge(enum)
end
end
Ok much to notice here:
Some examples what this means:
Set.new
=> #<Set: {}>
Set.new([1,2,2,3])
=> #<Set: {1, 2, 3}>
Set.new(["ape", "APE", "aPe"]) { |val| val.downcase }
#<Set: {"ape"}>
A second possibility is hidden at the bottom of the file:
module Enumerable
def to_set(klass = Set, *args, &block)
klass.new(self, *args, &block)
end
end
Some examples:
%w{hello, hello, you}.to_set
=> #<Set: {"hello,", "you"}>
%w{hello, hello, world, "!"}.to_set {|val| val.upcase }
=> #<Set: {"HELLO,", "WORLD,", ""!""}>
Here is a third way:
def self.[](*ary)
new(ary)
end
This is pretty nice trick. It produces a nice shortcut to create a set.
Set[1,2,3,4]
#<Set: {1, 2, 3, 4}>
A nice feature of sets is, that they support set arithmetic. The implementation is pretty straightforward, this is one of the instances where Ruby's syntax really shines :)