class Set
Very similar to a set but uses a specific callback (defaults to &:name) for object identity.
Definitions
def initialize(contents = [])
Initialize a new set with optional initial contents.
Signature
-
parameter
contentsArray Initial objects to add to the set.
Implementation
def initialize(contents = [])
@table = {}
contents.each do |object|
add(object)
end
end
def freeze
Freeze the set.
Implementation
def freeze
return self if frozen?
@table.freeze
super
end
def initialize_dup(other)
Initialize a duplicate of another set.
Signature
-
parameter
otherSet The set to duplicate.
Implementation
def initialize_dup(other)
@table = other.table.dup
end
def identity(object)
Get the identity of an object for use as a hash key.
Signature
-
parameter
objectObject The object to get the identity for.
-
returns
String The object's name.
Implementation
def identity(object)
object.name
end
def add(object)
Add an object to the set.
Signature
-
parameter
objectObject The object to add.
-
raises
KeyError If an object with the same identity already exists.
Implementation
def add(object)
if include?(object)
raise KeyError, "Object #{identity(object)} already exists!"
end
@table[identity(object)] = object
end
def delete(object)
Delete an object from the set.
Signature
-
parameter
objectObject The object to delete.
-
returns
Object, nil The deleted object, or nil if not found.
Implementation
def delete(object)
@table.delete(identity(object))
end
def include?(object)
Check if the set includes an object.
Signature
-
parameter
objectObject The object to check for.
-
returns
Boolean True if the set includes the object.
Implementation
def include?(object)
@table.include?(identity(object))
end
def each(&block)
Iterate over each object in the set.
Implementation
def each(&block)
@table.each_value(&block)
end
def slice(names)
Get a subset of objects by their names.
Signature
-
parameter
namesArray<String> The names of objects to retrieve.
-
returns
Array<Object> The objects with the given names.
Implementation
def slice(names)
names.collect{|name| @table[name]}
end