Class: Peruby::PerlHash

Inherits:
Object
  • Object
show all
Defined in:
lib/peruby/runtime/perl_hash.rb

Overview

Perl HV represented as string keys and mutable scalar cells.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cells = {}, &on_set) ⇒ PerlHash

Returns a new instance of PerlHash.



8
9
10
11
12
# File 'lib/peruby/runtime/perl_hash.rb', line 8

def initialize(cells = {}, &on_set)
  @cells = cells
  @iterator = 0
  @on_set = on_set
end

Instance Attribute Details

#cellsObject (readonly)

Returns the value of attribute cells.



6
7
8
# File 'lib/peruby/runtime/perl_hash.rb', line 6

def cells
  @cells
end

Instance Method Details

#delete(key) ⇒ Object



31
32
33
34
# File 'lib/peruby/runtime/perl_hash.rb', line 31

def delete(key)
  @iterator = 0
  @cells.delete(key.to_s)&.get
end

#each_pairObject



41
42
43
44
45
# File 'lib/peruby/runtime/perl_hash.rb', line 41

def each_pair
  pair = @cells.to_a[@iterator]
  @iterator = pair ? @iterator + 1 : 0
  pair
end

#exists?(key) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
# File 'lib/peruby/runtime/perl_hash.rb', line 27

def exists?(key)
  @cells.key?(key.to_s)
end

#fetch(key) ⇒ Object



14
15
16
# File 'lib/peruby/runtime/perl_hash.rb', line 14

def fetch(key)
  @cells[key.to_s]&.get
end

#keysObject



36
37
38
39
# File 'lib/peruby/runtime/perl_hash.rb', line 36

def keys
  @iterator = 0
  @cells.keys
end

#listObject



47
48
49
# File 'lib/peruby/runtime/perl_hash.rb', line 47

def list
  @cells.flat_map { |key, cell| [Scalar.new(key), cell] }
end

#replace_cell(key, cell) ⇒ Object



51
52
53
54
55
# File 'lib/peruby/runtime/perl_hash.rb', line 51

def replace_cell(key, cell)
  @iterator = 0
  key = key.to_s
  cell ? @cells[key] = cell : @cells.delete(key)
end

#slot(key) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/peruby/runtime/perl_hash.rb', line 18

def slot(key)
  key = key.to_s
  unless @cells.key?(key)
    @iterator = 0
    @cells[key] = Scalar.new { |value| @on_set&.call(key, value) }
  end
  @cells[key]
end