Class: DataStructures101::Hash::Bucket

Inherits:
Object
  • Object
show all
Defined in:
lib/data_structures_101/hash/bucket.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBucket

Returns a new instance of Bucket.



7
8
9
# File 'lib/data_structures_101/hash/bucket.rb', line 7

def initialize()
    @table = []
end

Instance Attribute Details

#tableObject (readonly)

Returns the value of attribute table.



5
6
7
# File 'lib/data_structures_101/hash/bucket.rb', line 5

def table
  @table
end

Instance Method Details

#[](key) ⇒ Object



11
12
13
# File 'lib/data_structures_101/hash/bucket.rb', line 11

def [](key)
    find(key)
end

#[]=(key, value) ⇒ Object



15
16
17
# File 'lib/data_structures_101/hash/bucket.rb', line 15

def []=(key, value)
    insert(key, value)
end

#delete(key) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/data_structures_101/hash/bucket.rb', line 40

def delete(key) 
    idx = @table.find_index {|_key, _| _key == key}
    return nil if idx.nil?

    value = @table[idx].last
    @table[idx] = @table.last if idx != @table.size - 1
    @table.pop
    value
end

#eachObject



50
51
52
53
54
55
56
# File 'lib/data_structures_101/hash/bucket.rb', line 50

def each
    return enum_for(:each) unless block_given?

    @table.each do |key, value|
        yield(key, value)
    end
end

#find(key) ⇒ Object



35
36
37
38
# File 'lib/data_structures_101/hash/bucket.rb', line 35

def find(key)
    pair = @table.find {|_key, _| _key == key}
    pair.nil? ? nil : pair.last
end

#insert(key, value) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/data_structures_101/hash/bucket.rb', line 19

def insert(key, value)
    idx = @table.find_index {|_key, _| _key == key} 

    if idx.nil?
        @table << [key, value]
        return nil
    else
        value, @table[idx][1] = @table[idx][1], value
        return value
    end
end

#sizeObject



31
32
33
# File 'lib/data_structures_101/hash/bucket.rb', line 31

def size
    @table.size
end