Class: DataStructures101::Hash::Bucket
- Inherits:
-
Object
- Object
- DataStructures101::Hash::Bucket
- Defined in:
- lib/data_structures_101/hash/bucket.rb
Overview
Utility class to manipulate (key, pairs) that have same hash code.
Instance Attribute Summary collapse
- #table ⇒ Object readonly
Instance Method Summary collapse
- #[](key) ⇒ Object
- #[]=(key, value) ⇒ Object
- #delete(key) ⇒ Object
- #each ⇒ Object
- #find(key) ⇒ Object
-
#initialize ⇒ Bucket
constructor
A new instance of Bucket.
- #insert(key, value) ⇒ Object
- #size ⇒ Object
Constructor Details
#initialize ⇒ Bucket
Returns a new instance of Bucket.
12 13 14 |
# File 'lib/data_structures_101/hash/bucket.rb', line 12 def initialize @table = [] end |
Instance Attribute Details
#table ⇒ Object (readonly)
10 11 12 |
# File 'lib/data_structures_101/hash/bucket.rb', line 10 def table @table end |
Instance Method Details
#[](key) ⇒ Object
16 17 18 |
# File 'lib/data_structures_101/hash/bucket.rb', line 16 def [](key) find(key) end |
#[]=(key, value) ⇒ Object
20 21 22 |
# File 'lib/data_structures_101/hash/bucket.rb', line 20 def []=(key, value) insert(key, value) end |
#delete(key) ⇒ Object
45 46 47 48 49 50 51 52 53 |
# File 'lib/data_structures_101/hash/bucket.rb', line 45 def delete(key) idx = @table.find_index { |table_key, _| table_key == key } return nil if idx.nil? value = @table[idx].last @table[idx] = @table.last if idx != @table.size - 1 @table.pop value end |
#each ⇒ Object
55 56 57 58 59 60 61 |
# File 'lib/data_structures_101/hash/bucket.rb', line 55 def each return enum_for(:each) unless block_given? @table.each do |key, value| yield(key, value) end end |
#find(key) ⇒ Object
40 41 42 43 |
# File 'lib/data_structures_101/hash/bucket.rb', line 40 def find(key) pair = @table.find { |table_key, _| table_key == key } pair.nil? ? nil : pair.last end |
#insert(key, value) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/data_structures_101/hash/bucket.rb', line 24 def insert(key, value) idx = @table.find_index { |table_key, _| table_key == key } if idx.nil? @table << [key, value] return nil else value, @table[idx][1] = @table[idx][1], value return value end end |
#size ⇒ Object
36 37 38 |
# File 'lib/data_structures_101/hash/bucket.rb', line 36 def size @table.size end |